angular - 需要在父组件打开时检测子组件的任何变化
问题描述
我想检测我是否对子组件进行了任何更改,然后父组件应该知道这些更改。
所以我在子组件中有一些文本编辑器,当我在该文本编辑器中进行任何更改时,父组件应该知道它。
我尝试过的代码:
父组件:
@ViewChildren(EditorComponent) editor: EditorComponent;
ngAfterViewChecked(){
console.info(this.editor.isDirty);
}
但这总是返回undefined
。
在子组件中,我默认将 isdirty 提到为 false。
您能否指导我如何进行此操作。
解决方案
您可以使用@Output Decorator
将数据从子组件发送到父组件。
在子组件中创建一个事件发射器并将值传递给事件发射器。
@Output() childValueChange = new EventEmitter();
this.childValueChange.emit(value);
在父组件 HTML
<app-parent-component (childValueChange)='save($event)'></app-parent-component>
组件.ts
save(event){
// Here you will get the value which child has emitted
console.log(event);
}