这是因为子组件之前已经接收到了输入属性,并且输入属性的引用仍然存在于子组件中。为了解决这个问题,我们需要使用Observables或者Subject(可以通过RxJS进行功能实现),并将值传递给子组件的订阅者。这样,即使值发生更改,子组件也会收到更新的值。以下是示例代码:
父组件:
import { Component, OnInit } from '@angular/core';
import { Subject } from 'rxjs';
@Component({
selector: 'parent-component',
template: `
`
})
export class ParentComponent implements OnInit {
name: string;
name$: Subject = new Subject();
ngOnInit() {
this.name$.next(this.name);
}
updateName() {
// Update name here using patchValue()
this.name$.next(this.name);
}
}
子组件:
import { Component, Input } from '@angular/core';
@Component({
selector: 'child-component',
template: `
{{ name }}
`
})
export class ChildComponent {
@Input() name: string;
}