1、在跟模块下导入
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
FormArrayComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
2、在相应组建的Ts.文件代码
import { Component, OnInit } from "@angular/core";
import { FormArray, FormControl, FormGroup } from "@angular/forms";
import { Validators } from "@angular/forms";
@Component({
selector: "app-form-array",
templateUrl: "./form-array.component.html",
styleUrls: ["./form-array.component.css"]
})
export class FormArrayComponent implements OnInit {
constructor() {}
formGroup = new FormGroup({
aliases: new FormArray([new FormControl("", Validators.required)])
});
ngOnInit() {}
// 从formGroup里获取formArray对象,方法名为此FormArray的实例对象名
get ali() {
return this.formGroup.get("aliases") as FormArray;
}
// 往formArray里添加控件
addAlias() {
this.ali.push(new FormControl("", Validators.required));
}
onSubmit() {
console.warn(this.formGroup.value);
}
}
3、HTML文件示例
<form [formGroup]="formGroup" (ngSubmit)="onSubmit()" >
<div formArrayName="aliases">
<h3>Aliases</h3>
<button (click)="addAlias()">Add Alias</button>
<div *ngFor="let address of ali.controls; let i = index">
<label>
Alias:
<input type="text" [formControlName]="i" />
</label>
</div>
</div>
<button type="submit" [disabled]="!formGroup.valid">Submit</button>
</form>