Help Angular by taking a 1 minute survey!Go to surveyHome

NgModel

Creates a FormControl instance from a domain model and binds it to a form control element.

See more...

See also

NgModule

Selectors

  • [ngModel]:not([formControlName]):not([formControl])

Properties

Property Description
control: FormControl Read-only.
viewModel: any

Internal reference to the view model value.

@Input()
name: string

Tracks the name bound to the directive. The parent form uses this name as a key to retrieve this control's value.

@Input('disabled')
isDisabled: boolean

Tracks whether the control is disabled.

@Input('ngModel')
model: any

Tracks the value bound to this directive.

@Input('ngModelOptions')
options: { name?: string; standalone?: boolean; updateOn?: FormHooks; }

Tracks the configuration options for this ngModel instance.

name: An alternative to setting the name attribute on the form control element. See the example for using NgModel as a standalone control.

standalone: When set to true, the ngModel will not register itself with its parent form, and acts as if it's not in the form. Defaults to false.

updateOn: Defines the event upon which the form control value and validity update. Defaults to 'change'. Possible values: 'change' | 'blur' | 'submit'.

@Output('ngModelChange')
update: EventEmitter

Event emitter for producing the ngModelChange event after the view model updates.

path: string[] Read-only.

Returns an array that represents the path from the top-level form to this control. Each index is the string name of the control on that level.

formDirective: any Read-only.

The top-level directive for this control if present, otherwise null.

validator: ValidatorFn | null Read-only.

Synchronous validator function composed of all the synchronous validators registered with this directive.

asyncValidator: AsyncValidatorFn | null Read-only.

Async validator function composed of all the async validators registered with this directive.

Inherited from NgControl

Inherited from AbstractControlDirective

Template variable references

Identifier Usage
ngModel #myTemplateVar="ngModel"

Description

The FormControl instance tracks the value, user interaction, and validation status of the control and keeps the view synced with the model. If used within a parent form, the directive also registers itself with the form as a child control.

This directive is used by itself or as part of a larger form. Use the ngModel selector to activate it.

It accepts a domain model as an optional Input. If you have a one-way binding to ngModel with [] syntax, changing the value of the domain model in the component class sets the value in the view. If you have a two-way binding with [()] syntax (also known as 'banana-box syntax'), the value in the UI always syncs back to the domain model in your class.

To inspect the properties of the associated FormControl (like validity state), export the directive into a local template variable using ngModel as the key (ex: #myVar="ngModel"). You then access the control using the directive's control property, but most properties used (like valid and dirty) fall through to the control anyway for direct access. See a full list of properties directly available in AbstractControlDirective.

Using ngModel on a standalone control

The following examples show a simple standalone control using ngModel:

import {Component} from '@angular/core'; @Component({ selector: 'example-app', template: ` <input [(ngModel)]="name" #ctrl="ngModel" required> <p>Value: {{ name }}</p> <p>Valid: {{ ctrl.valid }}</p> <button (click)="setValue()">Set value</button> `, }) export class SimpleNgModelComp { name: string = ''; setValue() { this.name = 'Nancy'; } }
      
      
  1. import {Component} from '@angular/core';
  2.  
  3. @Component({
  4. selector: 'example-app',
  5. template: `
  6. <input [(ngModel)]="name" #ctrl="ngModel" required>
  7.  
  8. <p>Value: {{ name }}</p>
  9. <p>Valid: {{ ctrl.valid }}</p>
  10. <button (click)="setValue()">Set value</button>
  11. `,
  12. })
  13. export class SimpleNgModelComp {
  14. name: string = '';
  15.  
  16. setValue() { this.name = 'Nancy'; }
  17. }

When using the ngModel within <form> tags, you'll also need to supply a name attribute so that the control can be registered with the parent form under that name.

In the context of a parent form, it's often unnecessary to include one-way or two-way binding, as the parent form syncs the value for you. You access its properties by exporting it into a local template variable using ngForm such as (#f="ngForm"). Use the variable where needed on form submission.

If you do need to populate initial values into your form, using a one-way binding for ngModel tends to be sufficient as long as you use the exported form's value rather than the domain model's value on submit.

Using ngModel within a form

The following example shows controls using ngModel within a form:

import {Component} from '@angular/core'; import {NgForm} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate> <input name="first" ngModel required #first="ngModel"> <input name="last" ngModel> <button>Submit</button> </form> <p>First name value: {{ first.value }}</p> <p>First name valid: {{ first.valid }}</p> <p>Form value: {{ f.value | json }}</p> <p>Form valid: {{ f.valid }}</p> `, }) export class SimpleFormComp { onSubmit(f: NgForm) { console.log(f.value); // { first: '', last: '' } console.log(f.valid); // false } }
      
      
  1. import {Component} from '@angular/core';
  2. import {NgForm} from '@angular/forms';
  3.  
  4. @Component({
  5. selector: 'example-app',
  6. template: `
  7. <form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
  8. <input name="first" ngModel required #first="ngModel">
  9. <input name="last" ngModel>
  10. <button>Submit</button>
  11. </form>
  12. <p>First name value: {{ first.value }}</p>
  13. <p>First name valid: {{ first.valid }}</p>
  14. <p>Form value: {{ f.value | json }}</p>
  15. <p>Form valid: {{ f.valid }}</p>
  16. `,
  17. })
  18. export class SimpleFormComp {
  19. onSubmit(f: NgForm) {
  20. console.log(f.value); // { first: '', last: '' }
  21. console.log(f.valid); // false
  22. }
  23. }

Using a standalone ngModel within a group

The following example shows you how to use a standalone ngModel control within a form. This controls the display of the form, but doesn't contain form data.

<form> <input name="login" ngModel placeholder="Login"> <input type="checkbox" ngModel [ngModelOptions]="{standalone: true}"> Show more options? </form> <!-- form value: {login: ''} -->
      
      <form>
  <input name="login" ngModel placeholder="Login">
  <input type="checkbox" ngModel [ngModelOptions]="{standalone: true}"> Show more options?
</form>
<!-- form value: {login: ''} -->
    

Setting the ngModel name attribute through options

The following example shows you an alternate way to set the name attribute. The name attribute is used within a custom form component, and the name @Input property serves a different purpose.

<form> <my-person-control name="Nancy" ngModel [ngModelOptions]="{name: 'user'}"> </my-person-control> </form> <!-- form value: {user: ''} -->
      
      <form>
  <my-person-control name="Nancy" ngModel [ngModelOptions]="{name: 'user'}">
  </my-person-control>
</form>
<!-- form value: {user: ''} -->
    

Methods

A lifecycle method called when the directive's inputs change. For internal use only.

ngOnChanges(changes: SimpleChanges)
      
      ngOnChanges(changes: SimpleChanges)
    
Parameters
changes SimpleChanges

A object of key/value pairs for the set of changed inputs.

Lifecycle method called before the directive's instance is destroyed. For internal use only.

ngOnDestroy(): void
      
      ngOnDestroy(): void
    
Parameters

There are no parameters.

Returns

void

Sets the new value for the view model and emits an ngModelChange event.

viewToModelUpdate(newValue: any): void
      
      viewToModelUpdate(newValue: any): void
    
Parameters
newValue any

The new value emitted by ngModelChange.

Returns

void

Inherited from NgControl

Inherited from AbstractControlDirective