NgModelGroup

Creates and binds a FormGroup instance to a DOM element.

查看"说明"...

NgModule

选择器

属性

属性说明
@Input('ngModelGroup')
name: string

Tracks the name of the NgModelGroup bound to the directive. The name corresponds to a key in the parent NgForm.

继承自 AbstractFormGroupDirective

继承自 ControlContainer

继承自 AbstractControlDirective

模板变量参考手册

标识符用途
ngModelGroup#myTemplateVar="ngModelGroup"

说明

This directive can only be used as a child of NgForm (within <form> tags).

Use this directive 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.

Provide a name for the sub-group and it will become the key for the sub-group in the form's full value. If you need direct access, export the directive into a local template variable using ngModelGroup (ex: #myGroup="ngModelGroup").

Consuming controls in a grouping

The following example shows you how to combine controls together in a sub-group of the form.

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'}; } }
      
      
  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)">
  8. <p *ngIf="nameCtrl.invalid">Name is invalid.</p>
  9. <div ngModelGroup="name" #nameCtrl="ngModelGroup">
  10. <input name="first" [ngModel]="name.first" minlength="2">
  11. <input name="last" [ngModel]="name.last" required>
  12. </div>
  13. <input name="email" ngModel>
  14. <button>Submit</button>
  15. </form>
  16. <button (click)="setValue()">Set value</button>
  17. `,
  18. })
  19. export class NgModelGroupComp {
  20. name = {first: 'Nancy', last: 'Drew'};
  21.  
  22. onSubmit(f: NgForm) {
  23. console.log(f.value); // {name: {first: 'Nancy', last: 'Drew'}, email: ''}
  24. console.log(f.valid); // true
  25. }
  26.  
  27. setValue() { this.name = {first: 'Bess', last: 'Marvin'}; }
  28. }

继承自 AbstractFormGroupDirective

继承自 AbstractControlDirective