profileForm = this.fb.group({ firstName: ['张', Validators.required], lastName: ['以'], address: this.fb.group({ street: [''], city: [''], state: [''], zip: [''] }), aliases: this.fb.array([ this.fb.control('') ]) });
Step 3 - 访问FormArray控件
通过 getter 来访问控件比较便捷,也容易复用
使用 getter 语法来创建一个名为 aliases 的类属性
get aliases() { }
从父控件 FormGroup 中接收绰号的 FormArray 控件。
get aliases() { return this.profileForm.get('aliases') as FormArray; } addAlias() { this.aliases.push(this.fb.control('')); }
Step 3 - 在模板中显示表单数组
在模型中定义了 aliases 的 FormArray 之后,你必须把它加入到模板中供用户输入,使用 formArrayName 在这个
FormArray 和模板之间建立绑定。
<div formArrayName="aliases"> <h3>Aliases</h3> <button (click)="addAlias()">Add Alias</button> <div *ngFor="let address of aliases.controls; let i=index"> <!-- The repeated alias template --> <label> Alias: <input type="text" [formControlName]="i"> </label> </div> </div>
每当新的 alias 加进来时,FormArray 就会基于这个索引号提供它的控件。这将允许你在每次计算根控件的状态和值时跟踪每个控件。
全部代码
html
<form [formGroup]="profileForm" (ngSubmit)="onSubmit()"> <label> First Name: </label> <input type="text" formControlName="firstName" required> <label> Last Name: </label> <input type="text" formControlName="lastName"> <div formGroupName="address"> <h3>Address</h3> <label>Streel</label> <input type="text" formControlName="street"> <label>City</label> <input type="text" formControlName="city"> <label>State</label> <input type="text" formControlName="state"> <label>Zip Code</label> <input type="text" formControlName="zip"> </div> <div formArrayName="aliases"> <h3>Aliases</h3> <button (click)="addAlias()">Add Alias</button> <div *ngFor="let address of aliases.controls; let i=index"> <label>Alias</label> <input type="text" [formControlName]="i" > </div> </div> <button type="submit" [disabled]="!profileForm.valid">Submit</button> <p> <button (click)="updateProfile()">Update Profile</button> </p> <p> Form Status: {{ profileForm.status }} </p> </form>
js
import { Component, OnInit } from '@angular/core'; import {FormControl, FormGroup, FormBuilder, Validators, FormArray} from '@angular/forms'; @Component({ selector: 'app-profile-editor', templateUrl: './profile-editor.component.html', styleUrls: ['./profile-editor.component.css'] }) export class ProfileEditorComponent implements OnInit { profileForm = this.fb.group({ firstName: ['张', Validators.required], lastName: ['以'], address: this.fb.group({ street: [''], city: [''], state: [''], zip: [''] }), aliases: this.fb.array([ this.fb.control('') ]) }); constructor(private fb: FormBuilder) { } ngOnInit() { } onSubmit () { console.warn(this.profileForm.value); } updateProfile() { this.profileForm.patchValue({ firstName: 'Nancy', address: { street: '123 Drew Street' } }); } get aliases () { return this.profileForm.get('aliases') as FormArray; } addAlias() { this.aliases.push(this.fb.control('')); } }