When using two-way binding in Angular, it seems that the setter of the child component is called twice.
Here is a playground that demonstrates the issue. If the "Toggle from component" button is clicked, the isShown setter of toggler.component.ts is called twice. I reproduced the interesting code below:
Parent component
@Component({changeDetection: ChangeDetectionStrategy.OnPush})
export class AppComponent implements DoCheck {
public isShown = true;
public onToggle() {
this.isShown = !this.isShown;
}
}
Child component
@Component({changeDetection: ChangeDetectionStrategy.OnPush})
export class TogglerComponent {
public get isShown(): boolean {
return this._isShown;
}
@Input()
public set isShown(isShown: boolean) {
console.log('Entering setter component');
this._isShown = isShown;
this.isShownChange.emit(isShown);
}
@Output()
public isShownChange: EventEmitter<boolean> = new EventEmitter();
private _isShown: boolean = true;
public onToggle() {
this.isShown = !this.isShown;
}
}
How can I prevent the setter from being called twice? This behavior is problematic when the parent component initializes the bound variable asynchronously.