Angular ngModel Directive

What is Angular ngModel Directive?

ngModel Directive is basically used to bind the form’s fields like textbox, select, textarea etc. into Angular Template Driven Form.

without ngModel directive in the Angular Template Driven Form

If we do not define ngModel directive into the form field then we are not able to get the form field value.

Suppose, you have created form into user.component.html file


<form id="" #userForm="ngForm" class="form">
    <div class="col-md-12">
        <label>User Name:-</label><input type="text" name="userName" />
    </div>
    <div class="row col-md-12"></div>
    <div class="col-md-12">
        User Age:- <input type="text" name="userAge" />
    </div>
    <div>
        <input type="submit" class="btn btn-primary" (click)="submitUserForm(userForm)" name="userSubmit"
            value="Add User" />
    </div>
  </form>

Suppose, you have created form into user.component.ts file and put the below code.


import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.scss']
})
export class UserComponent implements OnInit {
  constructor() { }
  ngOnInit(): void {
  }
  submitUserForm(userForm:NgForm){
    console.log("userFormFieldsValues",userForm.value);
  }
}

After click the submit button then we are not able to get the form field value.

Add ngModel directive in the Angular Template Driven Form

So we need to add ngModel directive to add into the form field so that we can get the form field value.


<form id="" #userForm="ngForm" class="form">
    <div class="col-md-12">
        <label>User Name:-</label><input type="text" name="userName" ngModel/>
    </div>
    <div class="row col-md-12"></div>
    <div class="col-md-12">
        User Age:- <input type="text" name="userAge" ngModel/>
    </div>
    <div>
        <input type="submit" class="btn btn-primary" (click)="submitUserForm(userForm)" name="userSubmit"
            value="Add User" />
    </div>
  </form>