【发布时间】:2021-01-19 13:32:46
【问题描述】:
我正在使用 Angular Reactive FormArray 在添加按钮上添加多个输入。
我的设置中有多个 formGroup。当我尝试添加/推送输入时,出现“无法读取属性‘push’ of null”的错误。
我的 formGroup 设置有什么问题还是因为 formArray 中有多个 FormGroups
我的代码:HTML
<form [formGroup]="form">
<input type="checkbox" formControlName="published"> Published
<div *ngIf="form.controls.published.value">
<h2>Credentials</h2>
<button (click)="addCreds()">Add</button>
<div formArrayName="credentials" *ngFor="let creds of form.controls.credentials?.value; let i = index">
<ng-container [formGroupName]="i">
<input placeholder="Username" formControlName="username">
<input placeholder="Password" formControlName="password">
</ng-container>
</div>
</div>
</form>
角度代码:
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
published: true,
formArray: this.fb.array([
this.fb.group({
credentials: this.fb.array([]),
})
])
});
}
addCreds() {
const creds = this.form.get('credentials') as FormArray;
creds.push(this.fb.group({
username: '',
password: '',
}));
}
我也有https://stackblitz.com/edit/angular-form-array-example-hfmrm2
【问题讨论】: