angular - 无法读取 ngOnInit() Angular7 上未定义的属性“id”
问题描述
我是角度的初学者。问题实际上出在 EmployeeComponent.ts 中,如果我调用 this.resetForm();
,ngOnInit()
那么对话框的控件会在页面加载期间显示......但是在编辑期间,当它来自employeelistservice.formData
时,我不希望这种情况发生。我希望这两种功能都发生。
如果我remove this.resetForm();
在下面这个错误ngOnInit()
。(但编辑工作正常)注意:service.formData
包含字段 id、description 和 active
控制台日志错误:EmployeeComponent_Host.ngfactory.js?[sm]:1 错误类型错误:无法读取 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 是要打开的垫子对话框组件,因此您需要在 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);
}
现在您可以通过名称“数据”属性在 EmployeeComponent 上使用此数据
并且只在 ngOninit 中使用重置形式
ngOnInit() {
if (form != null)
form.resetForm();
}
完成保存后需要处理的其他事情,例如清除此数据
推荐阅读
- typescript - Threejs 几何和 TypeScript
- c# - Selenium.WebDriver.ChromeDriver 启动缓慢 - 为什么?
- azure - 在 Azure Web App 免费层上托管时,Docker 容器应用程序是否会进入睡眠状态?
- java - 通过 TFTP 传输的文件大小与主机上不同
- r - 如何在 R 中的 facet_grid 图上注释 R-sq 和 p 值?
- python - 无法打开文件(截断文件:eof = 7340032,sblock->base_addr = 0,stored_eof = 126651688)
- sql-server - 如何解决 xp_cmdshell 访问被拒绝错误?
- docker - 使用 docker-compose 停止 docker 容器
- javascript - 如何在纯 Javascript 中的单选按钮上使用 addEventListener?
- python - 如何使用 Tika 将 PDF 拆分为段落