Getter and Setter of Model object in Angular 4

AngularTypescript

Angular Problem Overview


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?

Angular Solutions


Solution 1 - Angular

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAVokinView Question on Stackoverflow
Solution 1 - AngularSpaceFozzyView Answer on Stackoverflow