Search code examples
angularangular-forms

Angular - NgForm - FormControl is undefined


I have a page where there is a simple NgForm form, I'm trying to disable a particular field after the page/view is loaded.

But I'm getting undefined exception:

ERROR TypeError: Cannot read property 'disable' of undefined

component.ts code:

import { Component, ViewChild, OnInit, AfterViewInit } from '@angular/core';
import { NgForm } from '@angular/forms';
@Component({
  selector: 'sub',
  templateUrl: 'sub.component.html'
})

export class SubComponent implements OnInit, AfterViewInit {
  @ViewChild('userForm') uf: NgForm;

  ngOnInit() {
    console.log(this.uf);
    console.log(this.uf.controls['name']) // this is null
  }

  ngAfterViewInit() {
    console.log('kasdkfj')
    console.log(this.uf);
    console.log(this.uf.controls['name']) // this is null 
            this.uf.controls['name'].disable(); // Exception here
  }

  onSubmit(value: any) {
    console.log(this.uf.controls['name']) // But this is NOT null
            this.uf.controls['name'].disable(); // NO Exception, works perfectly
    console.log(value); 
  }
}

HTML Code:

<div class="container">
  <h2>Form Data</h2>

      <form #userForm="ngForm" (ngSubmit)="onSubmit(userForm.value)">
       <div class="form-group"> 
             <label>Name</label>
              <input type="text" class="form-control" name="name" ngModel> 
        </div><br/>
        <div ngModelGroup="address">
              <div class="form-group"> 
                  <label>City</label>
                    <input type="text" class="form-control" name="city" ngModel> 
              </div><br/>
              <div class="form-group"> 
                  <label>Pin</label>
                    <input type="text" class="form-control" name="pin" ngModel> 
              </div><br/>
              <div class="form-group"> 
                  <label>State</label>
                    <input type="text" class="form-control" name="state" ngModel> 
              </div><br/>

        </div>
       <button type="submit" class="btn btn-primary" >Submit</button>
      </form>
  </div>

But same code when I do it on any button click or on submit it works without any issue.

Question: How to disable one of the field after the form is initialized?

Stackblitz Link


Solution

  • I'm not a fan of this, but this "fixes" the problem.

    ngAfterViewInit() {
        setTimeout(() => {
          console.log(this.uf.controls['name']) // this is null
          this.uf.controls['name'].disable(); // Exception here
        }, 0);
      }