我想将[(ngModel)]用于嵌套对象,但是给了我一个错误
Cannot read property 'mxn' of undefined
这些是我模型的数据结构:
company.model.ts
import Currency from './currency.model';
class Company {
_id: string;
name: string;
maxLimit: number;
source: [string];
deliveryMethod: [string];
currency: Currency;
date: Date;
constructor() {
this.name = '';
this.date = new Date();
this.maxLimit = 0;
this.source = [''];
this.deliveryMethod = [''];
this.currency.mxn = 0;
this.currency.php = 0;
}
}
export default Company;
currency.model.ts
class Currency {
mxn: number;
php: number;
constructor() {
this.mxn = 0;
this.php = 0;
}
}
export default Currency;
这是company.ts的一部分
public newCompany: Company = new Company();
companiesList: Company[];
editcompanies: Company[] = [];
和HTML
HTML页面中的我只需使用以下内容即可显示mxn
值:
<tr class="companies" *ngFor="let company of companiesList">
{{company.currency.mxn}}
但是当我想将它与ngModel
双向绑定结合使用来更新值并将其发送到数据库时,它无法正常工作。
[(ngModel)] = "newCompany.currency.mxn"
它产生上面提到的错误。
如果我使用
[(ngModel)] = "newCompany.currency"
它没有给我一个错误,但代码没用,因为我无法为mxn
分配任何值。
我必须说[(ngModel)] = "newCompany.name"
它可以正常使用,我可以更新名称。
后端工作正常,因为我和Postman一起尝试过。问题是角度方面。
所以问题是我的数据结构是否正确如何对嵌套对象使用双向绑定?
答案 0 :(得分:2)
公司模型的细微变化应该足够了:
class Company {
_id: string;
name: string;
maxLimit: number;
source: [string];
deliveryMethod: [string];
currency: Currency = new Currency(); // provide an instance, otherwise this field will be undefined
date: Date;
constructor() {
this.name = '';
this.date = new Date();
this.maxLimit = 0;
this.source = [''];
this.deliveryMethod = [''];
this.currency.mxn = 0;
this.currency.php = 0;
}
}
export default Company;
&#13;
答案 1 :(得分:2)
currency: Currency;
...
constructor() {
...
this.currency.mxn = 0;
this.currency.php = 0;
}
在您实例化Currency
的实例之前,mxn和php还不存在。实例currency
为空。它不包含任何属性。
currency: Currency;
...
constructor() {
...
this.currency = new Currency(); // invoke Currency constructor, create mxn and php with value 0, therefore you dont need this.currency.mxn = 0 and same to php
}
答案 2 :(得分:1)
看起来您没有在构造函数中实例化货币字段。尝试更改
currency: Currency;
到
currency = new Currency();
它可能与您的companiesList
合作,因为可能(我猜这里)您的后端为您实例化它们。当你实例化我假设你自己做的newCompany
时,它不起作用,导致失踪的new Currency()