使用角形数组时的上下文信息

时间:2018-11-19 01:12:37

标签: angular angular-reactive-forms

我正在使用Reactive Forms中的数组,并尝试在表单控件旁边显示一些上下文信息。例如,一个客户可能有很多地址,我可以很容易地显示此数组,但我也想显示地址类型,即文本而不是表单控件。

例如,我有以下数据模型:

const backingModel = {
  addresses: [
    {
      name: 'Home',
      zipCode: '76106'
    },
    {
      name: 'Billing',
      zipCode: '09210'
    },
    {
      name: 'Shipping',
      zipCode: '90210'
    }
  ]
};

然后我用来在表单组内部构建一个数组

this.formGroup = this.fb.group({
  addresses: this.fb.array([
    this.fb.group({
      zipCode: [backingModel.addresses[0].zipCode, Validators.required]
    }),
    this.fb.group({
      zipCode: [backingModel.addresses[1].zipCode, Validators.required],
    }),
    this.fb.group({
      zipCode: [backingModel.addresses[2].zipCode, Validators.required]
    })
  ])
});

显示此内容的HTML

<form [formGroup]="formGroup">
  <div formArrayName="addresses" *ngFor="let item of formGroup.get('addresses').controls; let i = index">
    <div [formGroupName]="i">
      <h3>???? How to get adress description </h3>
      <input type="text" formControlName="zipCode" />
      <hr />
    </div>
  </div>
</form>

在此示例中,我将如何传递地址名称,以便以表格形式使用它?

2 个答案:

答案 0 :(得分:1)

将其添加到您的支持模型中,然后仅显示它?

let output = ['a', 'b', 'c', 'd', 'e', 'f'],
    data = output.
           join('').
           match(/(.+?){2}/g).
           map(s => s.split('').join(',')).join('\n');


console.log(data);

答案 1 :(得分:1)

您的HTML应该如下所示:

<form [formGroup]="formGroup">
    <div formArrayName="addresses" >
      <div *ngFor="let item of backingModel.addresses; let i = index" [formGroupName]="i">
        <h3>{{ item.name }}</h3>
        <input type="text" formControlName="zipCode" />
        <hr />
      </div>
    </div>
</form>

请注意,我要遍历模型,而不是表单控件。

在component.ts文件中,您需要设置formGroup如下所示:

this.formGroup = fb.group({
  "addresses": fb.array([
    fb.group({ "zipCode": fb.control('Home')}),
    fb.group({ "zipCode": fb.control('Billing')}),
    fb.group({ "zipCode": fb.control('Shipping')})
  ])
});

但是,这是硬编码的,因此,请使用您的backingModel来生成此代码:

this.formGroup = fb.group({
  "addresses": fb.array(
    this.backingModel.addresses.map(t => 
      fb.group({ "zipCode": [t.zipCode, Validators.required] })
    ))
  });
}

以下是最后的component.ts

import { Component } from '@angular/core';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';

@Component({
  selector: 'cmp',
  templateUrl: './cmp.component.html',
  styleUrls: ['./cmp.component.css']
})
export class CmpComponent {
  formGroup: FormGroup;
  backingModel: any = {
    addresses: [
      {
        name: 'Home',
        zipCode: '76106'
      },
      {
        name: 'Billing',
        zipCode: '09210'
      },
      {
        name: 'Shipping',
        zipCode: '90210'
      }
    ]
  };
  constructor(private fb: FormBuilder) {

    this.formGroup = fb.group({
      "addresses": fb.array(
        this.backingModel.addresses.map(t => 
          fb.group({ "zipCode": [t.zipCode, Validators.required] })
        ))
      });
    }
 }