在 Angular 7 中,当父组件更改值时不会自动更新子组件。为了解决这个问题,你可以使用 @Input
装饰器来监听父组件的值变化,并手动更新子组件。
下面是一个示例代码:
父组件:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
`
})
export class ParentComponent {
parentValue = 0;
updateValue() {
this.parentValue += 1;
}
}
子组件:
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-child',
template: `
Value from parent: {{ value }}
`
})
export class ChildComponent implements OnChanges {
@Input() value: number;
ngOnChanges(changes: SimpleChanges) {
if (changes.value) {
this.value = changes.value.currentValue;
}
}
}
在这个示例中,ParentComponent
定义了一个名为 parentValue
的变量,并在点击按钮时更新它。子组件 ChildComponent
使用 @Input
装饰器来接收来自父组件的值,并在 ngOnChanges
生命周期钩子中手动更新子组件的值。
这样,当你点击按钮时,父组件的值会更新,并且子组件会随之更新。