【问题标题】:How to render dynamic forms properly in Angular Reactive Forms?如何在 Angular Reactive Forms 中正确呈现动态表单?
【发布时间】:2021-02-04 12:33:42
【问题描述】:

我有一个返回 JSON 数组的 API 请求,如下所示:

{
  "address": {
    "addressLine1": "499 Linden Boulevard",
    "addressLine2": "Apt 4b",
    "city": "Moraida",
    "province": "Kansas",
    "postalCode": "21763",
    "country": "USA"
  },
  "phones": [
    {
      "phoneNumber": "+1 (887) 502-2245",
      "phoneType": 3
    },
    {
      "phoneNumber": "+1 (823) 536-7452",
      "phoneType": 1
    }
  ],
  "email": "latti.sh@hotmail.com"
}

“phones”JSON 数组是动态的.. 意味着它可能有一个或多个或没有.. 我正在尝试使用动态反应式表单,所以我定义了我的表单组,如下所示

addressInfoForm = new FormGroup({
  addressLine1: new FormControl('', [Validators.required]),
  addressLine2: new FormControl('', []),
  city: new FormControl('', [Validators.required]),
  province: new FormControl('', []),
  postalCode: new FormControl('', [Validators.required]),
  country: new FormControl({ value: '', disabled: true }, [Validators.required]),
  email: new FormControl('', [Validators.email]),
  phones: this.fb.array([this.fb.control('')]),
});

当我在onInit() 方法中收到我的 JSON 响应时,我正在设置这样的表单值:

this.addressInfoForm.setValue({
  addressLine1: this.clientIdentInfo.address.addressLine1,
  addressLine2: this.clientIdentInfo.address.addressLine2,
  city: this.clientIdentInfo.address.city,
  province: this.clientIdentInfo.address.province,
  postalCode: this.clientIdentInfo.address.postalCode,
  country: this.clientIdentInfo.address.country,
  email: this.clientIdentInfo.email,
  // how to set the phones
});

我确实构建了这样的 getphone() 和 AddPhone() 方法。

get phones() {
  return this.addressInfoForm.get('phones') as FormArray;
}

AddPhone() {
  this.phones.push(this.fb.control(''));
  this.phones.push(this.fb.control(''));
}

在我的 html 中,我正在尝试填充手机并能够通过 AddPhone() 方法添加新手机,如下所示:

<form *ngFor="let phone of phones.controls; let i=index;" 
   [formGroupName]="i" 
   formArrayName="phones">
        <mat-grid-list cols="4" rowHeight="90px" gutterSize="10px">
          <mat-grid-tile  [colspan]="1">
            <mat-form-field appearance="outline" class="form-field">
              <mat-label>Phone {{i + 1}}</mat-label>
              <input matInput class="input-field" formControlName="phoneNumber">
              <mat-icon matSuffix>local_phone</mat-icon>
            </mat-form-field>
          </mat-grid-tile>
          <mat-grid-tile>
            <mat-form-field appearance="outline" class="form-field">
              <mat-label>Phone Type</mat-label>
              <mat-select formControlName="phoneType">
                <mat-option *ngFor="let type of phoneTypes" [value]="type.phoneTypeId">
                  {{ type.phoneTypeName }}
                </mat-option>
              </mat-select>
            </mat-form-field>
          </mat-grid-tile>
        </mat-grid-list>
      </form>

很遗憾,这不起作用!有人可以帮助我以正确的方式实现这一目标吗?

【问题讨论】:

    标签: angular angular-reactive-forms


    【解决方案1】:

    您需要根据您的结果将手机控件添加到手机数组并将值修补到手机表单数组。

       this.addressInfoForm.patchValue({
          addressLine1: result.address.addressLine1,
          addressLine2: result.address.addressLine1,
          city: result.address.city,
          province: result.address.province,
          postalCode: result.address.postalCode,
          country: result.address.country,
          email: result.email
        });
    
        for (let i = 0; i < result.phones.length - 1; i++) {
          this.AddPhone();
        }
    
        result.phones.forEach((item, index) => {
          this.phones.get(index.toString()).patchValue({
            phoneNumber: item.phoneNumber,
            phoneType: item.phoneType
          });
        });
    

    这是您的 stackblitz 示例,您的解决方案: https://stackblitz.com/edit/angular-ivy-bhclwz?file=src/app/app.component.ts

    【讨论】:

    • 如果我想填充电话类型(例如:1:home、2:cell、3:work)怎么办……由于某种原因,它对我来说不起作用……每次用户单击添加电话,电话文本框和电话类型的下拉菜单应填充
    • 好的,根据您的输入,我将在我的 stackblitz 中进行更改。但根据您的要求,您需要将 formGroup 推送到 Formarray
    • 现在检查,我已经根据你的输入更新了我的答案和堆栈闪电@Riad
    • 是的,这就是我正在做的,但由于某种原因,我得到了错误:找不到名称为“0”的控件错误:找不到路径为“0-> phoneNumber”的控件错误:找不到带有路径的控件:'0 -> phoneType' 我正在更新我的 html
    • 不要在同一元素中使用 ngFor 、 formArrayName 和 FormGroup 参考 stackblitz
    猜你喜欢
    • 2020-12-30
    • 2020-12-26
    • 2023-04-06
    • 2017-10-01
    • 2020-04-07
    • 2021-03-04
    • 1970-01-01
    • 2019-01-13
    • 2023-03-04
    相关资源
    最近更新 更多