【发布时间】:2021-12-19 08:50:55
【问题描述】:
在Angular中使用two-way binding时,似乎调用了两次子组件的setter。
Here is a playground 证明了这个问题。如果单击“从组件切换”按钮,则会调用两次 toggler.component.ts 的 isShown 设置器。我复制了下面有趣的代码:
父组件
@Component({changeDetection: ChangeDetectionStrategy.OnPush})
export class AppComponent implements DoCheck {
public isShown = true;
public onToggle() {
this.isShown = !this.isShown;
}
}
子组件
@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;
}
}
如何防止 setter 被调用两次?当父组件异步初始化绑定变量时,这种行为是有问题的。
【问题讨论】:
标签: angular data-binding