NgModel

directive

npm Package @angular/forms
Module import { NgModel } from '@angular/forms';
Source forms/src/directives/ng_model.ts

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

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

Overview

@Directive({
    selector: '[ngModel]:not([formControlName]):not([formControl])',
    providers: [formControlBinding],
    exportAs: 'ngModel'
})
class NgModel extends NgControl implements OnChanges, OnDestroy {
  viewModel: any
  name: string
  isDisabled: boolean
  model: any
  options: {name?: string, standalone?: boolean}
  update: new EventEmitter()
  ngOnChanges(changes: SimpleChanges)
  ngOnDestroy(): void
  get control: FormControl
  get path: string[]
  get formDirective: any
  get validator: ValidatorFn|null
  get asyncValidator: AsyncValidatorFn|null
  viewToModelUpdate(newValue: any): void
  // inherited from forms/NgControl
  name: string|null
  valueAccessor: ControlValueAccessor|null
  get validator: ValidatorFn|null
  get asyncValidator: AsyncValidatorFn|null
  viewToModelUpdate(newValue: any): void
  // inherited from forms/AbstractControlDirective
  get control: AbstractControl|null
  get value: any
  get valid: boolean|null
  get invalid: boolean|null
  get pending: boolean|null
  get disabled: boolean|null
  get enabled: boolean|null
  get errors: ValidationErrors|null
  get pristine: boolean|null
  get dirty: boolean|null
  get touched: boolean|null
  get untouched: boolean|null
  get statusChanges: Observable<any>|null
  get valueChanges: Observable<any>|null
  get path: string[]|null
  reset(value: any = undefined): void
  hasError(errorCode: string, path?: string[]): boolean
  getError(errorCode: string, path?: string[]): any
}

How To Use

This directive can be used by itself or as part of a larger form. All you need is 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 will set 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 will always be synced back to the domain model in your class as well.

If you wish to inspect the properties of the associated FormControl (like validity state), you can also export the directive into a local template variable using ngModel as the key (ex: #myVar="ngModel"). You can then access the control using the directive's control property, but most properties you'll need (like valid and dirty) will fall through to the control anyway, so you can access them directly. You can see a full list of properties directly available in AbstractControlDirective.

The following is an example of 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'; }
}

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.

It's worth noting that in the context of a parent form, you often can skip one-way or two-way binding because the parent form will sync the value for you. You can access its properties by exporting it into a local template variable using ngForm (ex: #f="ngForm"). Then you can pass it where it needs to go on submit.

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.

Take a look at an example of 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
  }
}

To see ngModel examples with different form control types, see:

npm package: @angular/forms

NgModule: FormsModule

Selectors

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

Inputs

name bound to NgModel.name
disabled bound to NgModel.isDisabled
ngModel bound to NgModel.model
ngModelOptions bound to NgModel.options

Outputs

ngModelChange bound to NgModel.update

Exported as

Constructor

constructor(parent: ControlContainer, validators: Array<Validator|ValidatorFn>, asyncValidators: Array<AsyncValidator|AsyncValidatorFn>, valueAccessors: ControlValueAccessor[])

Members

viewModel: any

name: string

isDisabled: boolean

model: any

options: {name?: string, standalone?: boolean}

update: new EventEmitter()

ngOnChanges(changes: SimpleChanges)

ngOnDestroy(): void

get control: FormControl

get path: string[]

get formDirective: any

get validator: ValidatorFn|null

get asyncValidator: AsyncValidatorFn|null

viewToModelUpdate(newValue: any): void

© 2010–2017 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://v4.angular.io/api/forms/NgModel