我正在开发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'.
如果有人知道这个问题,请帮帮我。提前谢谢。
答案 0 :(得分:0)
要解决ExpressionChangedAfterItHasBeenCheckedError错误,您需要执行以下操作
添加到构造函数
private cd: ChangeDetectorRef
并在
中使用ngAfterViewInit() {
this.cd.detectChanges();
}