简体   繁体   English

Angular 7 表单 ExpressionChangedAfterItHasBeenCheckedError - 带有条件输入字段

[英]Angular 7 Form ExpressionChangedAfterItHasBeenCheckedError - with conditional Input Field

In one of my Angular 7 form, i am trying to make input fields based on other user input values.在我的 Angular 7 表单之一中,我试图根据其他用户输入值创建输入字段。 This is my html code.这是我的 html 代码。

div>
     <form [formGroup]="UserForm" #UserAdd="ngForm">               
        <mat-form-field>
            <mat-label>Gender</mat-label>
            <mat-select [(value)]="gentype" [formControl]="gendertype" required>
                <mat-option value="Male">Male</mat-option>
                <mat-option value="Female">Female</mat-option>
            </mat-select>
            <mat-error *ngIf="gendertype.hasError('required')">
                Gender is required.
            </mat-error>
        </mat-form-field>       
        <mat-form-field>
            <mat-label>Enrolled</mat-label>
            <mat-select [(value)]="enrol" [formControl]="enrolled" required>
                <mat-option value="No">No</mat-option>
                <mat-option value="Yes">Yes</mat-option>
            </mat-select>
        </mat-form-field>
        <mat-form-field class="form-element" *ngIf="enrol=='Yes'">
            <mat-label>User Preference</mat-label>
            <input matInput [placeholder]="gentype=='Male' ? 'Chicago' : 'Milan'" formControlName="preference" [required]="true" autocomplete="off">
            <mat-error *ngIf="preference.touched && !preference.required">
                Preference is required.
            </mat-error>
        </mat-form-field>
    </form>
    <button mat-raised-button color="primary" type="button" (click)="Save();"[disabled]="!UserAdd.form.valid">SAVE</button>
</div>

Component.ts code.组件.ts 代码。

private UserForm: FormGroup; 
ngOnInit() {
    this.createForm()   
  }
createForm() {
    console.log('in createForm')
    this.UserForm = new FormGroup({
            gendertype: new FormControl(), 
            enrolled: new FormControl('No'),
            preference: new FormControl('')
    })
  }  
get gendertype() { return this.UserForm.get('gendertype') }
get enrolled() { return this.UserForm.get('enrolled') }
get preference() { return this.UserForm.get('preference') }

Problem here I am facing, when user select "enrol-No" the form is in invalid state and SAVE button is disabled.我面临的问题是,当用户 select “enrol-No”时,表格无效 state 并且“保存”按钮被禁用。 i want to make preference input as "required" when taken.我想在拍摄时将偏好输入设为“必需”。 And if user select "enrol-Yes", i get error如果用户 select "enrol-Yes",我得到错误

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

Please suggest, where i am wrong and good way to handle the scenario.请提出建议,我在哪里错了,并且是处理这种情况的好方法。

You are getting this error because you have required attribute binding on preference form control.您收到此错误是因为您在首选项表单控件上具有必需的属性绑定。 When using reactive form you have to use validators functions to include validation to form control.使用响应式表单时,您必须使用验证器功能来将验证包括到表单控制中。

You can use disable property on FormControl to disable and enable formControl dynamically.您可以使用 FormControl 上的 disable 属性来动态禁用和启用 formControl。

component.ts组件.ts

createForm() {
    console.log('in createForm')
    this.UserForm = new FormGroup({
            gendertype: new FormControl(), 
            enrolled: new FormControl('No'),
            preference: new FormControl({value: '', disabled:true}, Validators.required)
    })
}  

In template side you can check wheather user enrolled or not, using entrolled control value property在模板方面,您可以使用已注册的控制值属性检查用户是否注册

component.html组件.html

<mat-form-field class="form-element" *ngIf="enrolled.value=='Yes'">
            <mat-label>User Preference</mat-label>
            <input matInput [placeholder]="gentype=='Male' ? 'Chicago' : 'Milan'" formControlName="preference"  autocomplete="off">
            <mat-error *ngIf="preference.touched && !preference.required"> 
                Preference is required.
            </mat-error>
   </mat-form-field>

Finally listen valueChanges on enrolled control to disable and enable preference form control dyanmically最后在注册控件上监听 valueChanges 以动态禁用和启用首选项表单控件

component.ts组件.ts

this.createForm();
    (this.enrolled as FormControl).valueChanges.subscribe(hasEntrolled=>{
     if(hasEntrolled === 'Yes'){
        (this.preference as FormControl).enable();
     }else{
          (this.preference as FormControl).disable();
     }
    });

Example例子

Instead of binding the controls using [formControl]='gendertype , use formControlName='gendertype' .不要使用[formControl]='gendertype绑定控件,而是使用formControlName='gendertype' This will bind using the form control instance not relying on the get function that you have created.这将使用不依赖于您创建的get function 的表单控件实例进行绑定。 This is what's triggering the expressionChanged error.这就是触发 expressionChanged 错误的原因。

If this doesn't help, please create a sample stackblitz for minimal reproduction.如果这没有帮助,请创建一个示例 stackblitz 以尽量减少复制。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 表单验证中的 Angular 5 ExpressionChangedAfterItHasBeenCheckedError - Angular 5 ExpressionChangedAfterItHasBeenCheckedError on form validation Angular:将查询参数绑定到 ExpressionChangedAfterItHasBeenCheckedError 中的表单字段结果 - Angular : bind query parameter to form field results in ExpressionChangedAfterItHasBeenCheckedError Angular ExpressionChangedAfterItHasBeenCheckedError 带有@Input() 到子视图 - Angular ExpressionChangedAfterItHasBeenCheckedError with @Input() to child views 自定义表单控件上的角度ExpressionChangedAfterItHaHasBeenCheckedError - Angular ExpressionChangedAfterItHasBeenCheckedError on custom form control 为显示错误的输入字段赋值:ExpressionChangedAfterItHasBeenCheckedError - Assigning value to input field showing error: ExpressionChangedAfterItHasBeenCheckedError Angular ExpressionChangedAfterItHasBeenCheckedError 输入。 OpenLayers Map - Angular ExpressionChangedAfterItHasBeenCheckedError on Input. OpenLayers Map 表单的Angular 4加载数据服务引发ExpressionChangedAfterItHaHasBeenCheckedError - Angular 4 Load Data Service for Form throws ExpressionChangedAfterItHasBeenCheckedError Angular Reactive Form手动验证给出了ExpressionChangedAfterItHaHasBeenCheckedError - Angular Reactive Form manual validate gives ExpressionChangedAfterItHasBeenCheckedError Angular 8 ExpressionChangedAfterItHasBeenCheckedError 反应形式的无线电验证 - Angular 8 ExpressionChangedAfterItHasBeenCheckedError radio validation on reactive form ExpressionChangedAfterItHasBeenCheckedError:角度 - ExpressionChangedAfterItHasBeenCheckedError: angular
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM