angular FormArray 中嵌套 FormGroup 问题解决
官方例子里说了FormArray可以嵌套group或者array,但只给了control的实例,这里记录一下嵌套group
ts文件:
import { Component } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { Validators } from '@angular/forms';
import { FormArray } from '@angular/forms';
@Component({
selector: 'app-profile-editor',
templateUrl: './profile-editor.component.html',
styleUrls: ['./profile-editor.component.css'],
})
export class ProfileEditorComponent {
profileForm = this.fb.group({
firstName: ['', Validators.required],
lastName: [''],
address: this.fb.group({
street: [''],
city: [''],
state: [''],
zip: [''],
}),
aliases: this.fb.array([]),
});
get aliases() {
return this.profileForm.get('aliases') as FormArray;
}
constructor(private fb: FormBuilder) {}
updateProfile() {
this.profileForm.patchValue({
firstName: 'Nancy',
address: {
street: '123 Drew Street',
},
});
}
addAlias() {
const temp = this.fb.group({
street: ['2'],
city: ['2'],
});
this.aliases.push(temp);
}
onSubmit() {
// TODO: Use EventEmitter with form value
console.warn(this.profileForm.value);
}
}
/*
Copyright Google LLC. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at https://angular.io/license
*/
html文件
<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
<label for="first-name">First Name: </label>
<input id="first-name" type="text" formControlName="firstName" required />
<label for="last-name">Last Name: </label>
<input id="last-name" type="text" formControlName="lastName" />
<div formGroupName="address">
<h2>Address</h2>
<label for="street">Street: </label>
<input id="street" type="text" formControlName="street" />
<label for="city">City: </label>
<input id="city" type="text" formControlName="city" />
<label for="state">State: </label>
<input id="state" type="text" formControlName="state" />
<label for="zip">Zip Code: </label>
<input id="zip" type="text" formControlName="zip" />
</div>
<div formArrayName="aliases">
<h2>Aliases</h2>
<button type="button" (click)="addAlias()">+ Add another alias</button>
<div
*ngFor="let alias of aliases.controls; let i = index"
[formGroupName]="i"
>
<label for="street-{{ i }}">Street-{{ i + 1 }}: </label>
<input id="street-{{ i }}" type="text" formControlName="street" />
<label for="city-{{ i }}">City-{{ i + 1 }}: </label>
<input id="city-{{ i }}" type="text" formControlName="city" />
</div>
</div>
<p>Complete the form to enable button.</p>
<button type="submit" [disabled]="!profileForm.valid">Submit</button>
</form>
<hr />
<p>Form Value: {{ profileForm.value | json }}</p>
<p>Form Status: {{ profileForm.status }}</p>
<button type="button" (click)="updateProfile()">Update Profile</button>
<!--
Copyright Google LLC. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at https://angular.io/license
-->

浙公网安备 33010602011771号