私はAngular2のコンポーネントを持っています。そのコンポーネントの中には、現在、@Input()が前に適用されたフィールドがたくさんあり、そのプロパティへのバインディングを可能にしています。
@Input() allowDay: boolean;
私がやりたいことは、get/setで実際にプロパティにバインドし、セッターで他のロジックを実行できるようにすることで、以下のようなものです。
_allowDay: boolean;
get allowDay(): boolean {
return this._allowDay;
}
set allowDay(value: boolean) {
this._allowDay = value;
this.updatePeriodTypes();
}
Angular2ではどのようにしてこれを行うのでしょうか?
Thierry Templierの提案に基づいて、これを変更しましたが、エラーが発生します。 Can'allowDay'は既知のネイティブプロパティではないので、バインドできません。
//@Input() allowDay: boolean;
_allowDay: boolean;
get allowDay(): boolean {
return this._allowDay;
}
@Input('allowDay') set allowDay(value: boolean) {
this._allowDay = value;
this.updatePeriodTypes();
}
以下のように、セッターの@Inputを直接設定することもできます。
_allowDay: boolean;
get allowDay(): boolean {
return this._allowDay;
}
@Input('allowDay')
set allowDay(value: boolean) {
this._allowDay = value;
this.updatePeriodTypes();
}
このプランクルを参照してください: https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview.
主にセッターのみにロジックを実装することに興味がある方。
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();
}
}
}
どの入力プロパティが変更されたかが問題にならない場合や、入力プロパティが1つしかない場合は、SimpleChanges
のインポートは必要ありません。
Angular Doc: OnChangesを参照してください。
**それ以外の場合:***。
private _allowDay: boolean;
@Input() set allowDay(value: boolean) {
this._allowDay = value;
this.updatePeriodTypes();
}
get allowDay(): boolean {
// other logic
return this._allowDay;
}
@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;
}
このプランカーをご覧ください。[https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview][1]