Angular2 @Input to a property with get/set

angular

I have an Angular2 component in that component it currently has a bunch fields that have @Input() applied before them to allow binding to that property, i.e.

@Input() allowDay: boolean;

What I would like to do is actually bind to a property with get/set, so that I can do some other logic in the setter, something like the following

_allowDay: boolean;
get allowDay(): boolean {
    return this._allowDay;
}
set allowDay(value: boolean) {
     this._allowDay = value;
     this.updatePeriodTypes();
}

how would I do this in Angular2?

Based on Thierry Templier suggestion I changed it to, but that throws the error Can't bind to 'allowDay' since it isn't a known native property :

//@Input() allowDay: boolean;
_allowDay: boolean;
get allowDay(): boolean {
    return this._allowDay;
}
@Input('allowDay') set allowDay(value: boolean) {
    this._allowDay = value;
    this.updatePeriodTypes();
}

Best Answer

You could set the @Input on the setter directly, as described below:

_allowDay: boolean;
get allowDay(): boolean {
    return this._allowDay;
}
@Input() set allowDay(value: boolean) {
    this._allowDay = value;
    this.updatePeriodTypes();
}

See this Plunkr: https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview.