[英]Cannot read property 'id' of undefined on ngOnInit() Angular7
我是棱角分明的初学者。 问题实际上在EmployeeComponent.ts中,如果我调用this.resetForm();
在ngOnInit()
然后在页面加载期间显示对话框的控件...但在编辑期间,当来自employeeselist时, service.formData
设置为null,我不希望这种情况发生。 我希望这两种功能都能实现。
如果我remove this.resetForm();
在ngOnInit()
。 (但编辑工作正常)注意: service.formData
包含字段id,description和active
Consolelog错误:EmployeeComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError:无法读取EmployeeComponent.push中未定义的属性“id”。
EmployeeComponent.ts
ngOnInit() {
this.resetForm();
}
resetForm(form ? : NgForm) {
if (form != null)
form.resetForm();
this.service.formData = {
id: null,
description: '',
active: true,
}
console.log(this.service.formData.id);
}
EmployeeListComponent.ts
onEdit(emp: Employee) {
this.service.formData = Object.assign({}, emp);
const dialogConfig = new MatDialogConfig();
dialogConfig.disableClose = true;
dialogConfig.autoFocus = true;
dialogConfig.width = "50%";
this.dialog.open(EmployeeComponent, dialogConfig);
}
Employee.component.html
<form #form="ngForm" autocomplete="off" >
<mat-grid-list cols="2">
<input type="hidden" name="id" #id="ngModel" [(ngModel)]="service.formData.id">
<mat-form-field>
<input name="description" matInput #description="ngModel" [(ngModel)]="service.formData.description" placeholder="Employee" required>
</mat-form-field>
<mat-checkbox matInput #active="ngModel" [(ngModel)]="service.formData.active" name="active">Active</mat-checkbox>
</mat-grid-list>
<button mat-raised-button color="primary" type="submit" [disabled]="form.invalid" (click)="onSubmit(form)">Submit</button>
<button mat-raised-button color="warn" style="margin-left: 6px;" (click)="onClear(form)">Clear</button>
</form>
这里EmployeeComponent是你要打开的mat对话框组件,所以你需要在EmployeeComponent的构造函数中使用下面的对话框提供数据
constructor(
@Inject(MAT_DIALOG_DATA) data)){}
当您打开对话框进行编辑时,需要设置数据
onEdit(emp: Employee) {
dialogConfig = new MatDialogConfig();
dialogConfig.disableClose = true;
dialogConfig.autoFocus = true;
dialogConfig.width = "50%";
// Provide your data here
dialogConfig.data = emp;
this.dialog.open(EmployeeComponent, dialogConfig);
}
现在,您可以通过名称“data”属性在EmployeeComponent上使用此数据
并且只在ngOninit中使用重置表单
ngOnInit() {
if (form != null)
form.resetForm();
}
您需要处理的其他事项,例如在完成保存后清除此数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.