简体   繁体   English

Angular 4中模型对象的Getter和Setter

[英]Getter and Setter of Model object in Angular 4

How can I make getter and setter work in my model class? 如何在模型类中使getter和setter工作?

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. 我打算在setter中做,但Angular 4忽略了我的模型的setter和getter。

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. 但是getter和setter不起作用。 What am I missing? 我错过了什么?

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. 将date属性声明为输入的方式看起来不正确,但如果没有看到所有代码,这是唯一的问题很难说。 Rather than using @Input('date') declare the date property like so: private _date: string; 而不是使用@Input('date')声明date属性,如下所示: private _date: string; . Also, make sure you are instantiating the model with the new keyword. 此外,请确保使用new关键字实例化模型。 Lastly, access the property using regular dot notation. 最后,使用常规点表示法访问该属性。

Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html : 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 这里有一个吸引人,展示了你想要做的事情: https ://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p = preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM