我有一个父组件,并将主窗体状态作为输入传递给子组件。有没有办法在子组件中保持表单状态更新?
父HTML:
<app-child [status]="myFormStatus"></app-child>在我的子控件中,我使用了status,但是当父控件中的myFormStatus值发生更改时,我如何通知该子控件?有没有办法调用父方法来获得最新的值?
发布于 2021-04-30 23:37:14
当指令的任何数据绑定属性更改时调用的生命周期挂钩。定义一个ngOnChanges()方法来处理这些更改。
interface OnChanges {
ngOnChanges(changes: SimpleChanges): void
}下面的代码片段显示了组件如何实现此接口,以便为输入属性定义更改时处理程序。
@Component({selector: 'child-cmp', template: `...`})
class ChildComponent implements OnChanges {
@Input() status!: any;
ngOnChanges(changes: SimpleChanges) {
// changes.status contains the old and the new value...
if(changes.status && changes.status.currentValue) {
// write your logic
}
}
}Angular为您提供了两种更改检测策略,default策略和onPush。
有了onPush,组件只依赖于它的输入并包含了不变性,变化检测策略将在以下情况下生效:输入引用发生变化;来自组件或其子组件的事件;显式运行变化检测`(componentRef.markForCheck());在视图中使用异步管道。
https://stackoverflow.com/questions/67333719
复制相似问题