I want to access form controls and disable some controls conditionally. In the following code, the form has no controls:
Component
export class OfferDialogComponent implements OnInit, AfterViewInit {
freemium = false;
@ViewChild('editForm') editForm: NgForm;
ngAfterViewInit(): void {
this.editForm.form.get("trialPeriod").disable();
}
}
Template
<form name="editForm" role="form" novalidate (ngSubmit)="save()" #editForm="ngForm">
How can I access and initialize form controls conditionally?
From Angular Docs
Template-driven forms delegate the creation of their form controls to directives. To avoid changed after checked errors, these directives take more than one cycle to build the entire control tree. That means you must wait until the next change detection cycle happens before manipulating any of the controls from within the component class.
For example, if you inject the form control with a
@ViewChild(NgForm)
query and examine it in thengAfterViewInit
lifecycle hook, you'll discover that it has no children. You must trigger a change detection cycle usingsetTimeout()
before you can extract a value from a control, test its validity, or set it to a new value.
Modified Code:
ngAfterViewInit(): void {
setTimeOut(() => {
this.editForm.form.get('trialPeriod').disable();
});
}
Or You could use ngAfterViewChecked
import { Component, ViewChild, ChangeDetectorRef } from '@angular/core';
class App {
constructor(private cdRef: ChangeDetectorRef) {}
ngAfterViewChecked() {
if (this.editForm.controls.name) this.editForm.form.get('name').disable();
this.cdRef.detectChanges();
//Forcing change detection to avoid ExpressionChangedAfterItHasBeenCheckedError
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With