ネストされたオブジェクトに [(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
mxn
HTMLページでは、次を使用するだけで値を表示できます:
<tr class="companies" *ngFor="let company of companiesList">
{{company.currency.mxn}}
ngModel
しかし、値を更新してデータベースに送信するために双方向バインディングで使用したい場合は機能しません。
[(ngModel)] = "newCompany.currency.mxn"
上記のエラーが発生します。使用
[(ngModel)] = "newCompany.currency"
してもエラーは発生しませんが、値を割り当てることができないため、コードは役に立ちませんmxn
。
[(ngModel)] = "newCompany.name"
これで問題なく動作し、名前を更新できると言わざるを得ません。
Postman で試してみたところ、バックエンドは正常に動作しました。問題は角度側です。
問題は、データ構造が正しい場合、ネストされたオブジェクトに双方向バインディングを使用するにはどうすればよいかということです。