我在该组件中有一个Angular2组件,它当前有一些字段,在它们之前应用@Input()以允许绑定到该属性,即
@Input() allowDay: boolean;
Run Code Online (Sandbox Code Playgroud)
我想要做的是实际使用get/set绑定到一个属性,这样我就可以在setter中做一些其他的逻辑,如下所示
_allowDay: boolean;
get allowDay(): boolean {
return this._allowDay;
}
set allowDay(value: boolean) {
this._allowDay = value;
this.updatePeriodTypes();
}
Run Code Online (Sandbox Code Playgroud)
我如何在Angular2中做到这一点?
根据Thierry Templier的建议我将其更改为,但是抛出错误无法绑定到'allowDay',因为它不是已知的本机属性:
//@Input() allowDay: boolean;
_allowDay: boolean;
get allowDay(): boolean {
return this._allowDay;
}
@Input('allowDay') set allowDay(value: boolean) {
this._allowDay = value;
this.updatePeriodTypes();
}
Run Code Online (Sandbox Code Playgroud)
Thi*_*ier 217
您可以直接在setter上设置@Input,如下所述:
_allowDay: boolean;
get allowDay(): boolean {
return this._allowDay;
}
@Input('allowDay')
set allowDay(value: boolean) {
this._allowDay = value;
this.updatePeriodTypes();
}
Run Code Online (Sandbox Code Playgroud)
请参阅此plunkr:https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p ? p = preview .
Mar*_*der 47
如果您主要对仅为setter实现逻辑感兴趣:
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
// [...]
export class MyClass implements OnChanges {
@Input() allowDay: boolean;
ngOnChanges(changes: SimpleChanges): void {
if(changes['allowDay']) {
this.updatePeriodTypes();
}
}
}
Run Code Online (Sandbox Code Playgroud)
SimpleChanges如果更改哪个输入属性或者只有一个输入属性无关紧要,则不需要导入.
除此以外:
private _allowDay: boolean;
@Input() set allowDay(value: boolean) {
this._allowDay = value;
this.updatePeriodTypes();
}
get allowDay(): boolean {
// other logic
return this._allowDay;
}
Run Code Online (Sandbox Code Playgroud)
@Paul Cavacas,我有同样的问题,我通过Input()在吸气剂上方设置装饰器来解决.
@Input('allowDays')
get in(): any {
return this._allowDays;
}
//@Input('allowDays')
// not working
set in(val) {
console.log('allowDays = '+val);
this._allowDays = val;
}
Run Code Online (Sandbox Code Playgroud)
看到这个plunker:https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p ? p = preview
| 归档时间: |
|
| 查看次数: |
150635 次 |
| 最近记录: |