我觉得这可能是一个基本问题,但经过一周的研究,我无法弄清楚我搞砸了什么。我承认我对Angular不太满意(2 ++)。
我正在尝试创建一个简单的CRUD系统。我在数据表的每一行上创建了一个按钮,并为每个行添加了单击事件。此事件将调用我的服务上的一个函数,该函数会将我重定向到我的表单并使用其数据填充我的var CurrentIncident。到目前为止,所有内容都很好连接,我可以按照预期从控制台看到数据:
返回示例数据:
{ description: "This is a test", data1: "Another test", data2: "Another test"}
下一步是使用NgModel在我的表单上设置双向绑定。所以我在输入中添加了这个。
<input placeholder="Description" value="" [(ngModel)]="CurrentIncident.Description">
但它返回错误:
错误类型错误:无法读取属性&#39;说明&#39;未定义的
有谁知道我搞砸了哪里?
按钮事件:
<button mat-mini-fab color="accent" (click)="CrudService.Edit_Incident(this.params.data)">
<mat-icon aria-label="Edit">description</mat-icon>
</button>
服务:
import { Injectable } from '@angular/core';
import { Incident_Model } from '../incident_model';
import {Router} from "@angular/router";
@Injectable()
export class CrudService {
constructor(private router: Router) {}
public CurrentIncident: Incident_Model[];
public Edit_Incident(data) {
this.CurrentIncident = data;
this.router.navigate(['form'])
console.log( this.CurrentIncident )
}
}
形式:
<mat-form-field fxFlex="40">
<input matInput placeholder="Description" value="">
</mat-form-field>
答案 0 :(得分:3)
在CrudService
类中,CurrentIncident
应该是一个数组,尽管构造函数中没有给出任何值。
这就是你模板中的原因
[(ngModel)]="CurrentIncident.Description"
CurrentIncident
最初为undefined
。
最重要的是,假设CurrentIncident
是一个数组,它将没有Description
属性。根据您的样本数据,您可能会使用类似
[(ngModel)]="CurrentIncident[0].description"
但只有在CurrentIncident
初始化后才会这样。
要在CurrentIncident
初始化之前防止错误,您可以使用*ngIf
<input placeholder="Description" value="" [(ngModel)]="CurrentIncident[0].description" *ngIf="CurrentIncident">