Access form controls inside ngAfterViewInit

Viewed 1487

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?

2 Answers

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 the ngAfterViewInit lifecycle hook, you'll discover that it has no children. You must trigger a change detection cycle using setTimeout() 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
  }
}

Define form control 
<input matInput placeholder="Email" [formControl]="emailFormControl">
 
In .ts :-
emailFormControl = new FormControl('default value');

and get value using this.emailFormControl.value

see : https://material.angular.io/components/input/examples

Related