在我需要添加电话的表单中,我看到在数据库中您正在保存一个字符串数组,其中包含我添加的电话号码,但是从数据库返回的值设置为表单时,只有显示第一个数组值。
我想以字符串格式显示所有包含电话数量的数组值。
component.html:
<div fxLayout="row" fxLayout.xs="column" fxLayoutAlign="start">
<div formArrayName="phones" fxFlex="30">
<div *ngFor="let phone of phones.controls; index as i">
<mat-form-field>
<input matInput [formControlName]="i" placeholder="Phone Number">
</mat-form-field>
</div>
</div>
<div fxFlex="30">
<button mat-raised-button class="blue" (click)="addPhone()">Add</button>
</div>
</div>
component.ts:
this.myForm = this._formBuilder.group({
phones: new FormArray([new FormControl('')]),
});
this.values$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe((values) => {
// values = {phones: ['999999', '88888', '77777']}
if (values) {
this.myForm.patchValue(values, { emitEvent: false });
}
});
get phones(): FormArray { return this.myForm.get('phones') as FormArray; }
addPhone(): void { this.phones.push(new FormControl('')); }
即使在数组内返回多个值也只会在表单上显示第一个数组值,我在做什么错了?
答案 0 :(得分:0)
patchValue
不会为您创建任何表单控件,因此,当您调用patchValue时,它仅设置表单数组中第一个表单控件的值,因为您仅创建了一个。
当您已经知道应该有多少个表单控件时,您必须为每个电话号码致电addPhone
或在describe中创建表单,但是您仍然需要创建与元素数一样多的表单控件数组。
this.myForm = this._formBuilder.group({
phones: new FormArray(),
});
this.values$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe((values) => {
if (values && values.phones) {
phones.forEach(phone => this.addPhone(phone));
}
});
get phones(): FormArray { return this.myForm.get('phones') as FormArray; }
addPhone(phone = ''): void { this.phones.push(new FormControl(phone)); }