反应形式动态表单验证中的角度6“ ExpressionChangedAfterItHaHasBeenCheckedError”添加和删除

时间:2018-07-19 06:42:44

标签: angular angular-reactive-forms angular-forms

我正在使用Angular 6反应性表单,如果我动态添加和添加新的验证器,则出现错误是

  

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

.ts文件

    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文件

    <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>

如果我删除动态验证程序,则效果很好

此错误不会影响我的流程,但会在控制台中引发错误

如何处理此错误

2 个答案:

答案 0 :(得分:0)

尝试进入ngAfterViewInit

<dataConfig>
<dataSource type="JdbcDataSource" driver="com.microsoft.sqlserver.jdbc.SQLServerDriver" url="jdbc:sqlserver://127.0.0.1\SQL2017;databaseName=mydatabase"   user="sa" password="mypassword"/>

    <document>
      <entity name="Product"  
        pk="Id"
        query="select Id, [Name] from Product"
        deltaImportQuery="SELECT Id, [Name] from Product WHERE Id='${dih.delta.id}'"
        deltaQuery="SELECT Id FROM Product  WHERE updated_at > '${dih.last_index_time}'"
        >
         <field column="Id" name="Id"/>
         <field column="Name" name="Name"/>       
      </entity>
    </document>
</dataConfig>

答案 1 :(得分:0)

带有* ngIf的div的内容会导致错误。试试这个:

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