簡體   English   中英

無法在ngOnInit()Angular7上讀取未定義的屬性“id”

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM