Angular 4中的Model对象的Getter和Setter [英] Getter and Setter of Model object in Angular 4

查看:198
本文介绍了Angular 4中的Model对象的Getter和Setter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在模型类中使用吸气剂和吸气剂?

How can I make getter and setter work in my model class?

我的目标是在输入包含日期的更新后计算所选日期的整数值.我本来打算用setter来做的,但是Angular 4忽略了我模型的setter和getter.

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.

我的模型班:

export class MyModel {
    @Input('date')
    get date(): String {
        console.log('Getting date');
        ...
    }

    set date(val) {
        console.log('Setting date: ' + val);
        ...
    }
}

我的模板:

...
<input class="form-control" name="dp" [(ngModel)]="model.date">
...

但是getter和setter不起作用.我想念什么?

But getter and setter don't work. What am I missing?

推荐答案

将date属性声明为输入的方式看起来不正确,但很难说这是否是唯一的问题,而无需查看所有代码.而不是像这样使用@Input('date')声明date属性:private _date: string;.另外,请确保使用new关键字实例化模型.最后,使用常规点符号访问该属性.

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.

对照 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);
}

这是一个小矮人,展示了您想做的事: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview

And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview

这篇关于Angular 4中的Model对象的Getter和Setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆