gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:25:59 26 4
gpt4 key购买 nike

我想将 [(ngModel)] 用于嵌套对象,但给我一个错误

无法读取未定义的属性“mxn”

这些是我的模型的数据结构:

公司.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;

货币.模型.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 双向绑定(bind)一起使用以更新值并将其发送到数据库时,它不起作用。

[(ngModel)] = "newCompany.currency.mxn"它会产生上面提到的错误。如果我使用[(ngModel)] = "newCompany.currency" 它没有给我一个错误,但代码是无用的,因为我无法为 mxn 分配任何值。

我不得不说 [(ngModel)] = "newCompany.name" 它可以正常工作,我可以更新名称。

当我用 Postman 尝试时,后端工作正常。问题是 Angular 一面。

所以问题是,如果我的数据结构是正确的,我该如何对嵌套对象使用双向绑定(bind)?

最佳答案

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
}

关于angular - 双向绑定(bind) - 嵌套对象 - Angular - 无法读取未定义的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47702257/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com