问题描述
我有两个组件:
child
有一个 @input()
和一个 @Output()
。当收到@Output
的回调时,parent
可能会改变@Input
的值。
是否可以在发出 EventEmitter
后等待潜在的输入更改?
为了重现问题的一些代码:
@Component({
selector: 'app-child',templateUrl: './app-child.component.html'
})
export class ChildComponent {
@input() myInput: string;
@Output() myOutput: EventEmitter<any> = new EventEmitter();
public doEmit() {
this.myOutput.emit();
}
private doAfterEmit() {
// Do something with myInput - expect it to use the value updated by the parent.
}
}
@Component({
selector: 'app-parent',templateUrl: './app-parent.component.html'
})
export class ParentComponent {
public theInputValue: string;
public onEmitCallback() {
// Update theInputValue
}
}
app-parent.component.html
<app-child [myInput]="theInputValue" (myOutput)="onEmitCallback()"></app-child>
解决方法
我认为您可以使用 getter/setter 方法或 ngOnChanges
生命周期挂钩来查找输入的任何更改。
getter/setter 方法:
_myInput: string;
get myInput(): boolean {
// can do other stuff too
return this._myInput;
}
@Input() set myInput(value: string) {
this._myInput = string;
// do your other stuff (update the input value)
}
ngOnChanges
方法:
ngOnChanges(changes: SimpleChanges) {
// changes has other properties as well,like
// changes.myInput.firstChange,changes.myInput.previousValue,changes.myInput.currentValue
if (changes.myInput.currentValue !== changes.myInput.previousValue) {
// the value of myInput changed from previous,so do what you would like here.
}
}
对于您的情况,我会使用 getter/setter
方法。
您可以阅读更多相关信息here。