This is the archived documentation for Angular v6. Please visit angular.io to see documentation for the current version of Angular.

NgModelGroup

Creates and binds a FormGroup instance to a DOM element.

See more...

NgModule

Selectors

Properties

Property Description
@Input('ngModelGroup')
name: string

Inherited from AbstractFormGroupDirective

Inherited from ControlContainer

Inherited from AbstractControlDirective

Template variable references

Identifier Usage
ngModelGroup #myTemplateVar="ngModelGroup"

Description

This directive can only be used as a child of NgForm (or in other words, within <form> tags).

Use this directive if you'd like to create a sub-group within a form. This can come in handy if you want to validate a sub-group of your form separately from the rest of your form, or if some values in your domain model make more sense to consume together in a nested object.

Pass in the name you'd like this sub-group to have and it will become the key for the sub-group in the form's full value. You can also export the directive into a local template variable using ngModelGroup (ex: #myGroup="ngModelGroup").

import {Component} from '@angular/core'; import {NgForm} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <form #f="ngForm" (ngSubmit)="onSubmit(f)"> <p *ngIf="nameCtrl.invalid">Name is invalid.</p> <div ngModelGroup="name" #nameCtrl="ngModelGroup"> <input name="first" [ngModel]="name.first" minlength="2"> <input name="last" [ngModel]="name.last" required> </div> <input name="email" ngModel> <button>Submit</button> </form> <button (click)="setValue()">Set value</button> `, }) export class NgModelGroupComp { name = {first: 'Nancy', last: 'Drew'}; onSubmit(f: NgForm) { console.log(f.value); // {name: {first: 'Nancy', last: 'Drew'}, email: ''} console.log(f.valid); // true } setValue() { this.name = {first: 'Bess', last: 'Marvin'}; } }
      
      import {Component} from '@angular/core';
import {NgForm} from '@angular/forms';

@Component({
  selector: 'example-app',
  template: `
    <form #f="ngForm" (ngSubmit)="onSubmit(f)">
      <p *ngIf="nameCtrl.invalid">Name is invalid.</p>
    
      <div ngModelGroup="name" #nameCtrl="ngModelGroup">
        <input name="first" [ngModel]="name.first" minlength="2">
        <input name="last" [ngModel]="name.last" required>
      </div>
      
      <input name="email" ngModel> 
      <button>Submit</button>
    </form>
    
    <button (click)="setValue()">Set value</button>
  `,
})
export class NgModelGroupComp {
  name = {first: 'Nancy', last: 'Drew'};

  onSubmit(f: NgForm) {
    console.log(f.value);  // {name: {first: 'Nancy', last: 'Drew'}, email: ''}
    console.log(f.valid);  // true
  }

  setValue() { this.name = {first: 'Bess', last: 'Marvin'}; }
}
    

Inherited from AbstractFormGroupDirective

Inherited from AbstractControlDirective