NgModelGroup

Stable

Directive

What it does

Creates and binds a FormGroup instance to a DOM element.

How to use

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").

  1. import {Component} from '@angular/core';
  2. import {NgForm} from '@angular/forms';
  3. @Component({
  4. selector: 'example-app',
  5. template: `
  6. <form #f="ngForm" (ngSubmit)="onSubmit(f)">
  7. <p *ngIf="nameCtrl.invalid">Name is invalid.</p>
  8. <div ngModelGroup="name" #nameCtrl="ngModelGroup">
  9. <input name="first" [ngModel]="name.first" minlength="2">
  10. <input name="last" [ngModel]="name.last" required>
  11. </div>
  12. <input name="email" ngModel>
  13. <button>Submit</button>
  14. </form>
  15. <button (click)="setValue()">Set value</button>
  16. `,
  17. })
  18. export class NgModelGroupComp {
  19. name = {first: 'Nancy', last: 'Drew'};
  20. onSubmit(f: NgForm) {
  21. console.log(f.value); // {name: {first: 'Nancy', last: 'Drew'}, email: ''}
  22. console.log(f.valid); // true
  23. }
  24. setValue() { this.name = {first: 'Bess', last: 'Marvin'}; }
  25. }
  • npm package: @angular/forms

  • NgModule: FormsModule

Class Overview

class NgModelGroup extends AbstractFormGroupDirective implements OnInit, OnDestroy {
constructor(parent: ControlContainer, validators: any[], asyncValidators: any[])
name : string

}

Selectors

[ngModelGroup]

Exported as

ngModelGroup

Class Description

Constructor

constructor(parent: ControlContainer, validators: any[], asyncValidators: any[])

Class Details

exported from @angular/forms/index, defined in @angular/forms/src/directives/ng_model_group.ts