Rendering a dynamic form in angular using ControlValueAccessor causes ExpressionChangedAfterItHasBeenCheckedError

I would like to render an angular form dynamically, based on a json schema object that describes the fields. I would like to render multiple types of fields, but for this example I will only use text fields. The schema object could look like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>fields: any[] = [
{
key: 'field1',
label: 'Label 1',
type: 'text',
required: true
},
{
key: 'field2',
label: 'Label 2',
type: 'text',
required: true
}
]
</code>
<code>fields: any[] = [ { key: 'field1', label: 'Label 1', type: 'text', required: true }, { key: 'field2', label: 'Label 2', type: 'text', required: true } ] </code>
fields: any[] = [
    {
      key: 'field1',
      label: 'Label 1',
      type: 'text',
      required: true
    },
    {
      key: 'field2',
      label: 'Label 2',
      type: 'text',
      required: true
    }
]

Given the schema above, 2 text fields should be rendered

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>main.component.html
</code>
<code>main.component.html </code>
main.component.html
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><form [formGroup]="form">
<span *ngFor="let field of fields">
<app-dynamic-form-field [field]="field" [formControlName]="field.key"></app-dynamic-form-field>
<br>
</span>
</form>
</code>
<code><form [formGroup]="form"> <span *ngFor="let field of fields"> <app-dynamic-form-field [field]="field" [formControlName]="field.key"></app-dynamic-form-field> <br> </span> </form> </code>
<form [formGroup]="form">
    <span *ngFor="let field of fields">
        <app-dynamic-form-field [field]="field" [formControlName]="field.key"></app-dynamic-form-field>
        <br>
    </span>
</form>
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>main.component.ts
</code>
<code>main.component.ts </code>
main.component.ts
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>ngOnInit(): void {
const formGroup: any = {};
for(let field of this.fields) {
formGroup[field.key] = [null];
}
this.form = this.fb.group(formGroup);
this.form.valueChanges.subscribe(val => {
console.log(this.form.value);
})
}
</code>
<code>ngOnInit(): void { const formGroup: any = {}; for(let field of this.fields) { formGroup[field.key] = [null]; } this.form = this.fb.group(formGroup); this.form.valueChanges.subscribe(val => { console.log(this.form.value); }) } </code>
ngOnInit(): void {
    const formGroup: any = {};
    for(let field of this.fields) {
      formGroup[field.key] = [null];
    }

    this.form = this.fb.group(formGroup);

    this.form.valueChanges.subscribe(val => {
      console.log(this.form.value);
    })
  }
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>dynamic-form-field.component.html
</code>
<code>dynamic-form-field.component.html </code>
dynamic-form-field.component.html
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><app-text-field *ngIf="field.type == 'text'" [field]="field" [formControl]="formControl"></app-text-field>
<app-number-field *ngIf="field.type == 'number'" [field]="field" [formControl]="formControl"></app-number-field>
<app-select-field *ngIf="field.type == 'select'" [field]="field" [formControl]="formControl"></app-select-field>
</code>
<code><app-text-field *ngIf="field.type == 'text'" [field]="field" [formControl]="formControl"></app-text-field> <app-number-field *ngIf="field.type == 'number'" [field]="field" [formControl]="formControl"></app-number-field> <app-select-field *ngIf="field.type == 'select'" [field]="field" [formControl]="formControl"></app-select-field> </code>
<app-text-field *ngIf="field.type == 'text'" [field]="field" [formControl]="formControl"></app-text-field>

<app-number-field *ngIf="field.type == 'number'" [field]="field" [formControl]="formControl"></app-number-field>

<app-select-field *ngIf="field.type == 'select'" [field]="field" [formControl]="formControl"></app-select-field>
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>dynamic-form-field.component.ts
</code>
<code>dynamic-form-field.component.ts </code>
dynamic-form-field.component.ts
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { Component, Input, OnInit } from '@angular/core';
import { AbstractControl, ControlValueAccessor, FormBuilder, FormControl, FormGroup, NG_VALIDATORS, NG_VALUE_ACCESSOR, ValidationErrors, Validator, Validators } from '@angular/forms';
@Component({
selector: 'app-dynamic-form-field',
templateUrl: './dynamic-form-field.component.html',
styleUrls: ['./dynamic-form-field.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
multi: true,
useExisting: DynamicFormFieldComponent
},
{
provide: NG_VALIDATORS,
useExisting: DynamicFormFieldComponent,
multi: true
}
]
})
export class DynamicFormFieldComponent implements OnInit, ControlValueAccessor, Validator {
@Input({required: true})
field: any;
formControl!: FormControl;
onChange = (value:any) => {};
onTouched = () => {};
onValidationChange = () => {};
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
this.formControl = new FormControl();
this.formControl.valueChanges.subscribe(val => {
this.onTouched();
this.onChange(val);
this.onValidationChange();
})
}
// Control Value Accessor
writeValue(obj: any): void {
this.formControl.setValue(obj, {emitEvent: false});
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
if(isDisabled) {
this.formControl.disable({emitEvent: false});
}
else {
this.formControl.enable({emitEvent: false});
}
}
// Validator
validate(control: AbstractControl<any, any>): ValidationErrors | null {
if(this.formControl.valid) return null;
return {error: true};
}
registerOnValidatorChange(fn: () => void): void {
this.onValidationChange = fn;
}
}
</code>
<code>import { Component, Input, OnInit } from '@angular/core'; import { AbstractControl, ControlValueAccessor, FormBuilder, FormControl, FormGroup, NG_VALIDATORS, NG_VALUE_ACCESSOR, ValidationErrors, Validator, Validators } from '@angular/forms'; @Component({ selector: 'app-dynamic-form-field', templateUrl: './dynamic-form-field.component.html', styleUrls: ['./dynamic-form-field.component.scss'], providers: [ { provide: NG_VALUE_ACCESSOR, multi: true, useExisting: DynamicFormFieldComponent }, { provide: NG_VALIDATORS, useExisting: DynamicFormFieldComponent, multi: true } ] }) export class DynamicFormFieldComponent implements OnInit, ControlValueAccessor, Validator { @Input({required: true}) field: any; formControl!: FormControl; onChange = (value:any) => {}; onTouched = () => {}; onValidationChange = () => {}; constructor(private fb: FormBuilder) {} ngOnInit(): void { this.formControl = new FormControl(); this.formControl.valueChanges.subscribe(val => { this.onTouched(); this.onChange(val); this.onValidationChange(); }) } // Control Value Accessor writeValue(obj: any): void { this.formControl.setValue(obj, {emitEvent: false}); } registerOnChange(fn: any): void { this.onChange = fn; } registerOnTouched(fn: any): void { this.onTouched = fn; } setDisabledState(isDisabled: boolean): void { if(isDisabled) { this.formControl.disable({emitEvent: false}); } else { this.formControl.enable({emitEvent: false}); } } // Validator validate(control: AbstractControl<any, any>): ValidationErrors | null { if(this.formControl.valid) return null; return {error: true}; } registerOnValidatorChange(fn: () => void): void { this.onValidationChange = fn; } } </code>
import { Component, Input, OnInit } from '@angular/core';
import { AbstractControl, ControlValueAccessor, FormBuilder, FormControl, FormGroup, NG_VALIDATORS, NG_VALUE_ACCESSOR, ValidationErrors, Validator, Validators } from '@angular/forms';

@Component({
  selector: 'app-dynamic-form-field',
  templateUrl: './dynamic-form-field.component.html',
  styleUrls: ['./dynamic-form-field.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      multi: true,
      useExisting: DynamicFormFieldComponent
    },
    {
      provide: NG_VALIDATORS,
      useExisting: DynamicFormFieldComponent,
      multi: true
    }
  ]
})
export class DynamicFormFieldComponent implements OnInit, ControlValueAccessor, Validator {

  @Input({required: true})
  field: any;

  formControl!: FormControl;

  onChange = (value:any) => {};
  onTouched = () => {};
  onValidationChange = () => {};

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.formControl = new FormControl();

    this.formControl.valueChanges.subscribe(val => {
      this.onTouched();
      this.onChange(val);
      this.onValidationChange();
    })
  }


  // Control Value Accessor
  writeValue(obj: any): void {
    this.formControl.setValue(obj, {emitEvent: false});
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }

  setDisabledState(isDisabled: boolean): void {
    if(isDisabled) {
      this.formControl.disable({emitEvent: false});
    }
    else {
      this.formControl.enable({emitEvent: false});
    }
  }

  // Validator
  validate(control: AbstractControl<any, any>): ValidationErrors | null {
    if(this.formControl.valid) return null;
    return {error: true};
  }
  registerOnValidatorChange(fn: () => void): void {
    this.onValidationChange = fn;
  }

}
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>text-field.component.html
</code>
<code>text-field.component.html </code>
text-field.component.html
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><mat-form-field>
<input matInput
type="text"
[placeholder]="field.label"
[formControl]="formControl">
</mat-form-field>
</code>
<code><mat-form-field> <input matInput type="text" [placeholder]="field.label" [formControl]="formControl"> </mat-form-field> </code>
<mat-form-field>
    <input matInput
        type="text"
        [placeholder]="field.label"
        [formControl]="formControl">
</mat-form-field>
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>text-field.component.ts
</code>
<code>text-field.component.ts </code>
text-field.component.ts
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { Component, Input, OnInit } from '@angular/core';
import { AbstractControl, ControlValueAccessor, FormBuilder, FormControl, FormGroup, NG_VALIDATORS, NG_VALUE_ACCESSOR, ValidationErrors, Validator, Validators } from '@angular/forms';
@Component({
selector: 'app-text-field',
templateUrl: './text-field.component.html',
styleUrls: ['./text-field.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
multi: true,
useExisting: TextFieldComponent
},
{
provide: NG_VALIDATORS,
useExisting: TextFieldComponent,
multi: true
}
]
})
export class TextFieldComponent implements OnInit, ControlValueAccessor, Validator {
@Input({required: true})
field: any;
formControl!: FormControl;
onChange = (value:any) => {};
onTouched = () => {};
onValidationChange = () => {};
ngOnInit(): void {
this.formControl = new FormControl<string>('');
if(this.field.required) {
this.formControl.addValidators(Validators.required);
}
this.formControl.valueChanges.subscribe(val => {
this.onTouched();
this.onChange(val);
this.onValidationChange();
})
}
writeValue(obj: any): void {
this.formControl.setValue(obj, {emitEvent: false});
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
if(isDisabled) {
this.formControl.disable();
}
else {
this.formControl.enable();
}
}
// Validator
validate(control: AbstractControl<any, any>): ValidationErrors | null {
if(this.formControl.valid) return null;
return {error: true};
}
registerOnValidatorChange(fn: () => void): void {
this.onValidationChange = fn;
}
}
</code>
<code>import { Component, Input, OnInit } from '@angular/core'; import { AbstractControl, ControlValueAccessor, FormBuilder, FormControl, FormGroup, NG_VALIDATORS, NG_VALUE_ACCESSOR, ValidationErrors, Validator, Validators } from '@angular/forms'; @Component({ selector: 'app-text-field', templateUrl: './text-field.component.html', styleUrls: ['./text-field.component.scss'], providers: [ { provide: NG_VALUE_ACCESSOR, multi: true, useExisting: TextFieldComponent }, { provide: NG_VALIDATORS, useExisting: TextFieldComponent, multi: true } ] }) export class TextFieldComponent implements OnInit, ControlValueAccessor, Validator { @Input({required: true}) field: any; formControl!: FormControl; onChange = (value:any) => {}; onTouched = () => {}; onValidationChange = () => {}; ngOnInit(): void { this.formControl = new FormControl<string>(''); if(this.field.required) { this.formControl.addValidators(Validators.required); } this.formControl.valueChanges.subscribe(val => { this.onTouched(); this.onChange(val); this.onValidationChange(); }) } writeValue(obj: any): void { this.formControl.setValue(obj, {emitEvent: false}); } registerOnChange(fn: any): void { this.onChange = fn; } registerOnTouched(fn: any): void { this.onTouched = fn; } setDisabledState(isDisabled: boolean): void { if(isDisabled) { this.formControl.disable(); } else { this.formControl.enable(); } } // Validator validate(control: AbstractControl<any, any>): ValidationErrors | null { if(this.formControl.valid) return null; return {error: true}; } registerOnValidatorChange(fn: () => void): void { this.onValidationChange = fn; } } </code>
import { Component, Input, OnInit } from '@angular/core';
import { AbstractControl, ControlValueAccessor, FormBuilder, FormControl, FormGroup, NG_VALIDATORS, NG_VALUE_ACCESSOR, ValidationErrors, Validator, Validators } from '@angular/forms';

@Component({
  selector: 'app-text-field',
  templateUrl: './text-field.component.html',
  styleUrls: ['./text-field.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      multi: true,
      useExisting: TextFieldComponent
    },
    {
      provide: NG_VALIDATORS,
      useExisting: TextFieldComponent,
      multi: true
    }
  ]
})
export class TextFieldComponent implements OnInit, ControlValueAccessor, Validator {

  @Input({required: true})
  field: any;

  formControl!: FormControl;

  onChange = (value:any) => {};
  onTouched = () => {};
  onValidationChange = () => {};

  ngOnInit(): void {
    this.formControl = new FormControl<string>('');

    if(this.field.required) {
      this.formControl.addValidators(Validators.required);
    }

    this.formControl.valueChanges.subscribe(val => {
      this.onTouched();
      this.onChange(val);
      this.onValidationChange();
    })
  }

  writeValue(obj: any): void {
    this.formControl.setValue(obj, {emitEvent: false});
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }

  setDisabledState(isDisabled: boolean): void {
    if(isDisabled) {
      this.formControl.disable();
    }
    else {
      this.formControl.enable();
    }
  }

  // Validator
  validate(control: AbstractControl<any, any>): ValidationErrors | null {
    if(this.formControl.valid) return null;
    return {error: true};
  }
  registerOnValidatorChange(fn: () => void): void {
    this.onValidationChange = fn;
  }
}

So, basically, I would like to delegate the dynamic nature of the field to a “factory” component called DynamicFormFieldComponent. This works fine, but when the form is rendered, I get the following error:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>main.ts:5 ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value for 'ng-untouched': 'true'. Current value: 'false'. Expression location: MainComponent component. Find more at https://angular.io/errors/NG0100
at throwErrorIfNoChangesMode (core.mjs:11622:11)
at bindingUpdated (core.mjs:14851:17)
at checkStylingProperty (core.mjs:18266:32)
at Module.ɵɵclassProp (core.mjs:18174:5)
at NgControlStatus_HostBindings (forms.mjs:65:104)
at processHostBindingOpCodes (core.mjs:11853:21)
at refreshView (core.mjs:13544:9)
at detectChangesInView (core.mjs:13663:9)
at detectChangesInEmbeddedViews (core.mjs:13606:13)
at refreshView (core.mjs:13522:9)
</code>
<code>main.ts:5 ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value for 'ng-untouched': 'true'. Current value: 'false'. Expression location: MainComponent component. Find more at https://angular.io/errors/NG0100 at throwErrorIfNoChangesMode (core.mjs:11622:11) at bindingUpdated (core.mjs:14851:17) at checkStylingProperty (core.mjs:18266:32) at Module.ɵɵclassProp (core.mjs:18174:5) at NgControlStatus_HostBindings (forms.mjs:65:104) at processHostBindingOpCodes (core.mjs:11853:21) at refreshView (core.mjs:13544:9) at detectChangesInView (core.mjs:13663:9) at detectChangesInEmbeddedViews (core.mjs:13606:13) at refreshView (core.mjs:13522:9) </code>
main.ts:5 ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value for 'ng-untouched': 'true'. Current value: 'false'. Expression location: MainComponent component. Find more at https://angular.io/errors/NG0100
    at throwErrorIfNoChangesMode (core.mjs:11622:11)
    at bindingUpdated (core.mjs:14851:17)
    at checkStylingProperty (core.mjs:18266:32)
    at Module.ɵɵclassProp (core.mjs:18174:5)
    at NgControlStatus_HostBindings (forms.mjs:65:104)
    at processHostBindingOpCodes (core.mjs:11853:21)
    at refreshView (core.mjs:13544:9)
    at detectChangesInView (core.mjs:13663:9)
    at detectChangesInEmbeddedViews (core.mjs:13606:13)
    at refreshView (core.mjs:13522:9)

When I skip the inbetween DynamicFormComponent and instead render the fields in the main component, this error is not thrown. I have found the following solutions, which both seem too hacky to me and I would like to avoid them:

  1. Add a call to detect changes in main component inside ngAfterViewChecked
  2. use changeDetection: ChangeDetectionStrategy.OnPush inside main components @Component tag

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật