首页 > 解决方案 > 无法读取 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>

标签: angulargoogle-cloud-firestoreangular7

解决方案


这里 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();
}

完成保存后需要处理的其他事情,例如清除此数据


推荐阅读