提交表单后,Angular Material 7错误重置自动完成功能

时间:2019-02-14 22:12:19

标签: angular angular-material angular-material2

我有以下材料自动完成字段工作。问题是在成功提交数据后重置表单时出现错误。

target/daml/test_project2.dar

由于某种原因调用ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'company' of null TypeError: Cannot read property 'company' of null at MatAutocomplete.push../src/app/expense/expense-new/expense-new.component.ts.ExpenseNewComponent.displayFn [as displayWith] (expense-new.component.ts:93) 会完全将displayWith指令数据擦除为null。在重新加载页面时效果很好。

我的模板:

this.expenseForm.reset

我的提交功能:

<mat-form-field class="full-width-input">
  <input type="text" placeholder="Pick one" aria-label="Number" matInput formControlName="payee_id"
         [matAutocomplete]="auto">
  <mat-autocomplete #auto="matAutocomplete">
    <mat-option *ngFor="let payee of filteredOptions | async" [value]="payee">
      {{payee.company + " " + payee.first_name + " " + payee.last_name }}
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

自动完成过滤器功能:

onSubmit(formData: any, formDirective: FormGroupDirective) {
   this.expenseForm.value.payee_id = this.expenseForm.value.payee_id.id ;
   this.expenseService.addExpense(this.expenseForm.value).subscribe( success => {
       this.errorMessage = null;
       this.dataService.updateDataTable('new expense success');
       this.expense_expense_categories_attributes.controls = [];
      formDirective.resetForm(); //workaround for error state not resetting
      this.expenseForm.reset();
     },
     error => {
       this.errorMessage = error;
       console.log(this.errorMessage);
       this.openDialog();
     });
 }

1 个答案:

答案 0 :(得分:1)

displayWith函数取决于具有值的字段。重置表单将从字段中删除该值。因此,payee为空。这不是问题,这很正常-通常可以有一个空字段(尚未选择值)。您只需要确保您的displayFn函数能够处理:

displayFn(payee?: Payee): string | undefined {

  if (!payee) {
    return '';
  }

  if ((payee.company !== '' || null) && (payee.first_name !== '' || null  && payee.last_name !== '' || null)) {
    return payee ? payee.company  + ' - ' + payee.first_name + ' ' + payee.last_name : undefined;
  } else if (!payee.company) {
    return payee ? payee.first_name + ' ' + payee.last_name + ' ' + payee.company : undefined;
  } else if ((payee.company !== '' || null) && (payee.first_name === '' || null && payee.last_name === '' || null)) {
    return payee ? payee.company : undefined;
  }
}

如果您打算为自动完成功能设置一个默认值,以使得无法选择任何内容,那么您需要在重置表单后在payee_id控件上重新设置该默认值。