这可能是因为在第一个组件上绑定了同一个输入变量。在这种情况下,只有第一个组件能够获取新的输入值。可以使用一个服务来连接多个组件并共享输入值。示例如下:
在服务中创建一个Subject,在组件中使用该Subject来共享输入值:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class InputService {
private inputSubject = new Subject();
input$ = this.inputSubject.asObservable();
setInput(input: any) {
this.inputSubject.next(input);
}
}
在第一个组件中,在输入值更改时使用setInput来更新服务中的输入值:
import { Component } from '@angular/core';
import { InputService } from './input.service';
@Component({
selector: 'app-component-one',
template: `
`
})
export class ComponentOne {
constructor(private inputService: InputService) {}
updateInput(event) {
const input = event.target.value;
this.inputService.setInput(input);
}
}
在第二个组件中,使用服务中的输入值:
import { Component } from '@angular/core';
import { InputService } from './input.service';
@Component({
selector: 'app-component-two',
template: `
{{ input }}
`
})
export class ComponentTwo {
input: any;
constructor(private inputService: InputService) {}
ngOnInit() {
this.inputService.input$.subscribe(input => {
this.input = input;
});
}
}