Tenho um componente Angular2 nesse componente tem actualmente um monte de campos que têm @Input() aplicado antes deles para permitir a ligação a essa propriedade, ou seja
@Input() allowDay: boolean;
O que eu gostaria de fazer é ligar-me a uma propriedade com get/set, para que eu possa fazer alguma outra lógica no setter, algo como o seguinte
_allowDay: boolean;
get allowDay(): boolean {
return this._allowDay;
}
set allowDay(value: boolean) {
this._allowDay = value;
this.updatePeriodTypes();
}
como o faria em Angular2?
Com base na sugestão de Thierry Templier, mudei-o para, mas isso lança o erro Can't bind to 'allowDay' uma vez que é't uma propriedade nativa conhecida:
//@Input() allowDay: boolean;
_allowDay: boolean;
get allowDay(): boolean {
return this._allowDay;
}
@Input('allowDay') set allowDay(value: boolean) {
this._allowDay = value;
this.updatePeriodTypes();
}
Poderia colocar o @Input directamente no setter, como descrito abaixo:
_allowDay: boolean;
get allowDay(): boolean {
return this._allowDay;
}
@Input('allowDay')
set allowDay(value: boolean) {
this._allowDay = value;
this.updatePeriodTypes();
}
Ver este plunkr: https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview.
Se estiver principalmente interessado em implementar a lógica apenas para o **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();
}
}
}
A importação de SimpleChanges
não é necessária se não'não importa que propriedade de entrada foi alterada ou se tiver apenas uma propriedade de entrada.
Doc Angular: OnChanges[2] [Doc Angular: OnChanges][3
outros:
private _allowDay: boolean;
@Input() set allowDay(value: boolean) {
this._allowDay = value;
this.updatePeriodTypes();
}
get allowDay(): boolean {
// other logic
return this._allowDay;
}
@Paul Cavacas, tive o mesmo problema e resolvi-o colocando o Input()
decorador acima do getter.
@Input('allowDays')
get in(): any {
return this._allowDays;
}
//@Input('allowDays')
// not working
set in(val) {
console.log('allowDays = '+val);
this._allowDays = val;
}
Ver este mergulhador: https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview[2].