Reputation: 1111
How can I make getter and setter work in my model class?
My goal is to calculate integer value of the selected day when input, containing the date, updated. I was going to do it in setter, but Angular 4 ignores setter and getter of my model.
My model class:
export class MyModel {
@Input('date')
get date(): String {
console.log('Getting date');
...
}
set date(val) {
console.log('Setting date: ' + val);
...
}
}
My template:
...
<input class="form-control" name="dp" [(ngModel)]="model.date">
...
But getter and setter don't work. What am I missing?
Upvotes: 64
Views: 173171
Reputation: 2808
The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date')
declare the date property like so: private _date: string;
. Also, make sure you are instantiating the model with the new
keyword. Lastly, access the property using regular dot notation.
Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :
let passcode = "secret passcode";
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "secret passcode") {
this._fullName = newName;
}
else {
console.log("Error: Unauthorized update of employee!");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
console.log(employee.fullName);
}
And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview
Upvotes: 97