Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access form controls inside ngAfterViewInit

Tags:

angular

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?

like image 451
Halil Avatar asked Sep 02 '25 04:09

Halil


1 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
  }
}
like image 106
Vikas Avatar answered Sep 05 '25 00:09

Vikas