【发布时间】:2016-08-07 19:29:26
【问题描述】:
我在该组件中有一个 Angular2 组件,它当前有一堆字段,在它们之前应用了 @Input() 以允许绑定到该属性,即
@Input() allowDay: boolean;
我想要做的实际上是使用 get/set 绑定到一个属性,这样我就可以在 setter 中执行一些其他逻辑,如下所示
_allowDay: boolean;
get allowDay(): boolean {
return this._allowDay;
}
set allowDay(value: boolean) {
this._allowDay = value;
this.updatePeriodTypes();
}
我将如何在 Angular2 中做到这一点?
根据 Thierry Templier 的建议,我将其更改为,但这会引发错误 Can't bind to 'allowDay' 因为它不是已知的本机属性:
//@Input() allowDay: boolean;
_allowDay: boolean;
get allowDay(): boolean {
return this._allowDay;
}
@Input('allowDay') set allowDay(value: boolean) {
this._allowDay = value;
this.updatePeriodTypes();
}
【问题讨论】:
-
如何以及在哪里绑定到
[allowDay]="....". If the field (setter) name and the property name you want to use for binding are the same, you can omit the parameter for@Input(...)`。 -
如果您按照接受的答案所示的方式使用 get set,我很想知道您是如何设置单元测试的。
-
无论您最终做什么,请确保在您的设置器中放置一个断点、调试语句或计数器,以确保它只按预期触发一次。我刚刚发现我的每次更改检测运行都会更新,这会导致糟糕的性能和古怪的行为。
标签: angular