[英]Angular 2 ngModel Not Binding Object Property Defined In Class Definition
[英]Angular modular object property binding to ngModel
我有一個具有 1 組屬性和 X 模塊化屬性的對象,這些屬性根據數組添加,數組元素是對象名稱。 這非常適合在我的表格中顯示元素。 當我想將文本框綁定到我的模型時,我的問題就出現了,因為我收到一條錯誤消息,指出對象屬性不存在。 我已經包含了一個 *ngIf 來檢查該屬性是否存在,並且理論上它可以找到它。
這是我嘗試使用模塊化屬性名稱之一的 HTMl 代碼的一部分,我使用了一個我知道將存在的名稱來簡化調試,下一步是將其更改為完全模塊化:
<ng-container *ngIf="newWaste[0].hasOwnProperty('Metal')">
<ng-container [matColumnDef]="column" *ngFor="let column of displayedColumns | slice:2 let i = index">
<th mat-header-cell *matHeaderCellDef>{{ displayedColumns[i+2] }}</th>
<td mat-cell *matCellDef="let emp">
<input type="text" matInput placeholder="" value="{{ emp[column] }}" [(ngModel)]="newWaste[0].Metal" />
</td>
</ng-container>
</ng-container>
我也嘗試過計算屬性的數量,而不是直接檢查它是否存在,也沒有區別。
這是我的錯誤:
src/app/pages/waste/containers/waste-page/waste-page.component.html:33:132 - error TS2339: Property 'Metal' does not exist on type '{ measuredDate: Date; }'.
33 <input type="text" matInput placeholder="" value="{{ emp[column] }}" [(ngModel)]="newWaste[0].Metal" />
~~~~~
src/app/pages/waste/containers/waste-page/waste-page.component.ts:19:16
19 templateUrl: './waste-page.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component WastePageComponent.
我使用 Date 參數創建對象,其余的稍后添加。 綁定到日期完美無缺。
有什么建議么?
我使用 Date 參數創建對象,其余的稍后添加
這就是問題所在。 使用已經存在的Metal
屬性初始化newWaste
(如果它被初始化為undefined
則沒有問題),並且可能會調整newWaste
的 TS 類型,因此Metal
屬性是非可選的。 指向可能不存在的屬性的ngModel
的 Angular 對象。
考慮到整個初始化問題,我嘗試初始化一個空數組,而不是一個包含“measuredDate”屬性的對象的數組。
所以代替這個:
public newWaste = [{measuredDate: Date}];
我只是使用它,並在代碼中添加所有屬性:
public newWaste = [];
ngOnInit(): void {
//add the measureDate property
this.newWaste.push({measuredDate: new Date()});
//in other methods I add the more specific properties such as Metal
}
它以這樣的方式完美運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.