【问题标题】:Reactive form angular using FormArrayName使用 FormArrayName 的反应形式角度
【发布时间】:2019-02-26 07:00:01
【问题描述】:

在我的表单中我需要添加电话,我看到在数据库中您正在保存一个包含我添加的电话号码的字符串数组,但是从数据库返回的值设置为表单的那一刻,只有显示第一个数组值。

我想以字符串格式显示所有包含电话号码的数组值。

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('')); }

即使在数组中返回多个值也只会在我的表单上显示第一个数组值,我做错了什么?

【问题讨论】:

  • 也许订阅中只是拼写错误,其中参数称为vales,但您在订阅中使用valuesstackblitz.com 演示会加快问题查找速度。
  • 我在这里发布了错误的代码,但在我的代码中它是正确的......它只在屏幕上显示它包含在数组中的三个字符串中的第一个字符串

标签: html angular typescript angular-reactive-forms


【解决方案1】:

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)); }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-27
    • 2020-07-22
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    相关资源
    最近更新 更多