ngForm variable coming as undefined in component

I have created a form in angular , and used template driven approach to control it . Have used ngForm in the group , and tried to access form fields via name , but i get an error in the console referring – this.form is undefined .

My html looks like –

<form #createProjectForm="ngForm" (ngSubmit)="save()">
.....
 <mat-form-field appearance="outline">
              <mat-label>NMC/ODA Project No</mat-label>
              <input name="nmcNumbber" matInput autocomplete="off" />
            </mat-form-field>

And in the component file –

    import { Component, OnInit, ViewChild } from '@angular/core';
import { NgForm, Form } from '@angular/forms';

@Component({
  selector: 'app-create-project-details-fields',
  templateUrl: './create-project-details-fields.component.html',
  styleUrls: ['./create-project-details-fields.component.scss']
})
export class CreateProjectDetailsFieldsComponent implements OnInit {
  
  @ViewChild('createProjectForm') createForm : NgForm;
  constructor() { }

  ngOnInit(): void {
    this.getFormStatus();
  }

getFormStatus(){
  this.createForm.controls['nmcNumbber'].disable();
}

But the console gives –

enter image description here

Can anyone help me out in this ? TIA

18 thoughts on “ngForm variable coming as undefined in component”

  1. ngOnInit is too early. You need ngAfterContentInit or ngAfterViewInit. The view is not created in ngOnInit and @ViewChild('createProjectForm') createForm isn’t set, yet.

    Reply

Leave a Comment