Angular2.如何将对象数组用于反应形式中的控件 [英] Angular 2. How to use array of objects for controls in Reactive Forms

查看:80
本文介绍了Angular2.如何将对象数组用于反应形式中的控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为表单动态创建textarea.我有以下模型:

I need to dynamic create textarea for forms. I have the follwoing model:

this.fields = {
      isRequired: true,
      type: {
        options: [
          {
            label: 'Option 1',
            value: '1'
          },
          {
            label: 'Option 2',
            value: '2'
          }
        ]
      }
    };

和形式:

this.userForm = this.fb.group({
      isRequired: [this.fields.isRequired, Validators.required],
      //... here a lot of other controls
      type: this.fb.group({
         options: this.fb.array(this.fields.type.options),
      })
});

模板的一部分:

<div formGroupName="type">
       <div formArrayName="options">
         <div *ngFor="let option of userForm.controls.type.controls.options.controls; let i=index">
            <textarea [formControlName]="i"></textarea>
         </div>
      </div>
</div>

因此,如您所见,我有对象数组,并且我想使用label属性在textarea中显示它.现在,我看到[object Object].如果将options更改为简单的字符串数组,例如:['Option 1', 'Option 2'],则一切正常.但是我需要使用对象.因此,代替:

So, as you can see I have array of objects and I want to use label property to show it in a textarea. Now I see [object Object]. If I change options to simple string array, like: ['Option 1', 'Option 2'], then all works fine. But I need to use objects. So, instead of:

<textarea [formControlName]="i"></textarea>

我尝试过:

<textarea [formControlName]="option[i].label"></textarea>

但是,它不起作用.
如何使用对象数组?

But, it doesn't work.
How can I use array of objects?

这是 Plunkr

推荐答案

您需要添加一个FormGroup,其中包含您的labelvalue.这也意味着,由表单创建的对象与fields对象具有相同的构造.

You need to add a FormGroup, which contains your label and value. This also means that the object created by the form, is of the same build as your fields object.

ngOnInit() {
  // build form
  this.userForm = this.fb.group({
    type: this.fb.group({
      options: this.fb.array([]) // create empty form array   
    })
  });

  // patch the values from your object
  this.patch();
}

此后,我们使用OnInit中调用的方法对值进行修补:

After that we patch the value with the method called in your OnInit:

patch() {
  const control = <FormArray>this.userForm.get('type.options');
  this.fields.type.options.forEach(x => {
    control.push(this.patchValues(x.label, x.value))
  });
}

// assign the values
patchValues(label, value) {
  return this.fb.group({
    label: [label],
    value: [value]
  })    
}

最后,这是一个

这篇关于Angular2.如何将对象数组用于反应形式中的控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆