简体   繁体   中英

angular 6 "ExpressionChangedAfterItHasBeenCheckedError" in reactive form dynamic form validation add and remove

I am Using Angular 6 Reactive Form if i add new validators add and remove in dynamically i got a error is

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

.ts File

Form: FormGroup;
_UserTypes: any[] = [
  { _id: '1', User_Type: 'Sub Admin' },
  { _id: '2', User_Type: 'Manager' },
];
ShowReportsTo: Boolean = false;
constructor() { }
ngOnInit() {
  this.Form = new FormGroup({
    User_Type: new FormControl(null, Validators.required),
    Reports_To: new FormControl(null),
  });
}
UserType_Change() {
  const value = this.Form.controls['User_Type'].value;
  if (typeof value === 'object' && value !== null && value.User_Type !== 'Sub Admin') {
    this.ShowReportsTo = true;
    this.Form.controls['Reports_To'].setValidators([Validators.required]);
    this.Form.updateValueAndValidity();
  } else {
    this.ShowReportsTo = false;
    this.Form.controls['Reports_To'].clearValidators();
    this.Form.controls['Reports_To'].setErrors(null);
    this.Form.controls['Reports_To'].reset();
  }
}

.html file

<Form [formGroup]="Form">
  <div class="row">
    <div class="col-sm-6 Form_Select">
      <label>User Type :</label>
      <ng-select formControlName="User_Type (ngModelChange)=" UserType_Change()">
        <ng-option *ngFor="let Type of _UserTypes" [value]="Type">{{Type.User_Type}}</ng-option>
      </ng-select>
    </div>
    <div class="col-sm-6 Form_Select" *ngIf="ShowReportsTo">
      <label>Report To :</label>
      <input type="text" formControlName="Reports_To">
    </div>
  </div>
  <button (click)="submit()" [disabled]="Form.invalid"> Submit </button>
</Form>

if i remove the dynamic validators is working good

this error not affect my flow but throw the error in console

how to handle this error

The content of a div with *ngIf causes the error. Try this:

<ng-container *ngIf="ShowReportsTo">
   <div class="col-sm-6 Form_Select">
     ...
   </div>
</ng-container>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM