Angular2双向对象绑定方法

时间:2017-03-08 11:31:24

标签: json angular

Angular2双向数据绑定适用于json对象。 但我想绑定模型对象内部方法调用返回的对象。

我的JSON数据如下,

{
"partyId": "1001",
"partyName": "Lifecare Pharmaceuticals",
"partyShortName": null,
"partySecondaryName": null,
"partySecondaryShortName": null,
"sortingName": "Lifecare Pharma",
"mailingName": null,
"address": [{
    "type": "Personal",
    "addressLine1": "",
    "addressLine2": "",
    "addressLine3": "",
    "phone":""
},
{
    "type": "Office",
    "addressLine1": "",
    "addressLine2": "",
    "addressLine3": "",
    "phone":"9876543210"
}]}

打击是typescript model class

 export class Party {
    partyId: string;
    partyName: string;
    partyShortName: string;
    partySecondaryName: string;
    partySecondaryShortName: string;
    sortingName: string;
    mailingName: string;
    address: Array<Address>;

    getOfficeAddress(): Address {
        if(!address) {
            this.address = [];
            this.address.push(new Address());
        }
        let address ;
        this.saleReturnLineItemSet.forEach(addr => {
            if(addr.type == 'Office') {
                address = addr;
            }
        });
        return address;
    }
}

    export class Address {
        type: string;
        addressLine1: string;
        addressLine2: string;
        addressLine3: string;
        phone: string;
    }

这就是我试图在input标签中绑定它的方式。

<input name="phoneNo" [(ngModel)]="party.getOfficeAddress().phone" >

这样可以绑定吗? 或者请建议一种方法来进行此类绑定。

2 个答案:

答案 0 :(得分:1)

这将导致错误`表达式自上次检查后已更改。 绑定到每次调用时返回值的新实例的方法都不起作用。

如果您缓存创建的实例并返回此缓存实例,只要它的内容实际上不需要更改,那么它将正常工作。

答案 1 :(得分:1)

这是不可能的,因为双向绑定表明您可以读取到您绑定的属性。

您可以使用getset方法代替phone

get phone(): string {
        if(!this.address) {
            this.address = [];
            this.address.push(new Address());
        }
        let address ;
        this.saleReturnLineItemSet.forEach(addr => {
            if(addr.type == 'Office') {
                address = addr;
            }
        });
        return address.phone;
}

set phone(num: string) { //set the phone number }

在您的模板中,直接绑定到phone

<input name="phoneNo" [(ngModel)]="phone" >