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

two-way binding - nested object - angular - Cannot read property of undefined

我想将 [(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 尝试时,后端工作正常。问题是 angular 方面。

所以问题是如果我的数据结构是正确的,我怎样才能对嵌套对象使用双向绑定?

对您的公司模型稍作改动就足够了:

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;

您似乎没有在构造函数中实例化货币字段。尝试更改

currency: Currency;

currency = new Currency();

它可能与你的 companiesList 一起工作,因为可能(我在这里猜测)你的后端为你实例化它们。当你实例化我假设你自己做的 newCompany 时,它不工作导致缺少 new Currency()

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
}