0

我正在研究 angular4 项目。在这个项目中,当我尝试将表单分成不同的组件时遇到了一些问题。我会详细解释。我有以下表格:

<form [formGroup] = "BookingFormOne" (ngSubmit) = "submitBookingFormOne()">
    <CustomerSelection [customerInfo]="BookingFormOne"></CustomerSelection>
</form>

对于此表单,请遵循 ts 文件中的代码:

  this.BookingFormOne = this.formBuilder.group({
     customer_type         : ["new customer"],
     first_name            : [null, [Validators.required, Validators.pattern(this.regExpression)]],
     last_name             : [null, [Validators.pattern(this.regExpression)]],
     email_id              : [null, [Validators.required, Validators.pattern(this.emailRegExpression)]]
  });

在 html 之后的第二个组件 (CustomerSelection) 中:

<div [formGroup]="customerInfo">
  <div>
      <input type="radio" #new_customer name="customer_type" value="new customer" formControlName="customer_type" (change)="onCustomerTypeChange($event)"> 
  New Customer
      <input type="radio" #existing_customer name="customer_type" value="existing customer" formControlName="customer_type" (change)="onCustomerTypeChange($event)"> Existing customer
   </div>
  <div [hidden]="existing_customer?.checked" >
     <div>
        <div>
            <label>First Name</label>
            <div>
                <input placeholder="Ex: James" [(ngModel)]= "existingCustomerFilter.firstName" formControlName="first_name">
            </div>
        </div>
     </div>
  <div>
     <div>
        <label>Last Name</label>
        <div>
           <input placeholder="Ex: Lee" [(ngModel)]= "existingCustomerFilter.lastName" formControlName="last_name">
        </div>
     </div>
  </div>
  <div class="customer-field">
     <div>
        <label>Email Address</label>
        <div>
           <input placeholder="Ex: example@xyz.com" [(ngModel)]= "existingCustomerFilter.email" formControlName="email_id" (focusin)="emailExist = false" (focusout)="checkEmailExistance($event)">
        </div>
     </div>
  </div>
   </div>
   <div *ngIf="existing_customer?.checked">
      <div class="existingCustomer">
          <label>Select Customer</label>
          <SearchAutoComplete [data]="existingCustomerDetails" (onKeyup)="searchCustomers($event)" (getResult)="getSelectedCustomers($event)"></SearchAutoComplete>
      </div>
   </div>

第一次一切正常,但是当我尝试更改第二个组件中表单字段的值时,出现如下错误:

Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'.

如果有人知道这个问题,请帮助我。提前致谢。

4

1 回答 1

0

要解决 ExpressionChangedAfterItHasBeenCheckedError 错误,您需要执行以下操作

添加到构造函数中

private cd: ChangeDetectorRef

并用于

ngAfterViewInit() {
        this.cd.detectChanges();
    }
于 2017-09-28T09:12:08.480 回答