双向绑定 - 嵌套对象 - 角度 - 无法读取未定义的属性

时间:2017-12-07 19:18:36

标签: angular two-way-binding nest-nested-object

我想将[(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一起尝试过。问题是角度方面。

所以问题是我的数据结构是否正确如何对嵌套对象使用双向绑定?

3 个答案:

答案 0 :(得分:2)

公司模型的细微变化应该足够了:

&#13;
&#13;
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;
&#13;
&#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()