Skip to content
Related Articles

Related Articles

Improve Article

Angular forms NgModel Directive

  • Last Updated : 24 May, 2021
Geek Week

In this article, we are going to see what is NgModel in Angular 10 and how to use it. NgModel is used to create a top-level form group Instance, and it binds the form to the given form value.

Syntax:

<Input [(NgModel)= 'name']>

NgModule: Module used by NgModel is:

  • FormsModule

Selectors:

  • [ngModel]

Approach: 



  • Create the Angular app to be used
  • In app.component.ts make a variable that gives value to the input field.
  • In app.component.html make a form and use ngModel to get the value of the input.
  • Serve the angular app using ng serve to see the output.

Example 1:

app.component.ts




import { Component, Inject } from '@angular/core';
  import { PLATFORM_ID } from '@angular/core';
  import { isPlatformWorkerApp } from '@angular/common';
  
  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: [ './app.component.css' ]
  })
  export class AppComponent  {
    gfg: string = '';
  
  setValue() {
    this.gfg = 'GeeksforGeeks';
  }
  }


app.component.html




<h1>GeeksforGeeks</h1>
  
<input [(ngModel)]="gfg" #ctrl="ngModel" required>
  
  
<p>Value: {{ gfg }}</p>
  
  
  
<button (click)="setValue()">Set value</button>

Output:

Reference: https://angular.io/api/forms/NgModel




My Personal Notes arrow_drop_up
Recommended Articles
Page :