typescript 复选框的动态 FormArray

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40973370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:04:03  来源:igfitidea点击:

Dynamic FormArray for checkboxes

formsangularcheckboxtypescript

提问by zeevblu

I build a Form in angular2 and typescript. I try to add a list of checkboxes dynamically and it's not working for me, Where is my mistake?

我在 angular2 和 typescript 中构建了一个表单。我尝试动态添加一个复选框列表,但它对我不起作用,我的错误在哪里?

The template code:

模板代码:

<div formArrayName="categories">
   <div class="form-group" *ngFor="let category of updateDetailsForm.controls.categories.controls; let i = index">
      <label>
        <input type="checkbox" formControlName="{?{i}}">
          {?{category.name}}
      </label>
   </div>
</div>

The Typescript code:

打字稿代码:

updateDetailsForm: FormGroup;
private categories : Category[] = []

constructor(private router: Router,
            private ss : SearchService,
            private formBuilder: FormBuilder)
{
   this.initForm() // before the categories loaded
   this.ss.getAllCategories().subscribe(
     data => {
       this.categories = data
       this.initForm() // refresh the form with categories
     }
   )
 }

initForm() {
  let allCategories: FormArray = new FormArray([]);
  for (let i = 0; i < this.categories.length; i++) {
    allCategories.push(
      new FormGroup({
        'name': new FormControl([this.categories[i].categoryName])
      })
    )
  }
  this.updateDetailsForm = this.formBuilder.group({
    'image' : [''],
    'categories': allCategories
  })
}

This is my UI result, and I get the following error:

这是我的 UI 结果,我收到以下错误:

"inline template:17:33 caused by: control.registerOnChange is not a function"

“内联模板:17:33 引起:control.registerOnChange 不是函数”

enter image description here

在此处输入图片说明

The number of checkboxes is correct but the text is missing and I can't update the form result with user selection.

复选框的数量是正确的,但文本丢失,我无法使用用户选择更新表单结果。

  1. What the error means?

  2. How can I insert the right text next the checkbox?

  3. How can update the user selection into the form value?

  1. 错误是什么意思?

  2. 如何在复选框旁边插入正确的文本?

  3. 如何将用户选择更新为表单值?

采纳答案by silentsod

You've built out your form model in such a way that we'll need to access each FormGroupthat you pushed onto the array and then access the named control within:

您已经以这样一种方式构建了表单模型,我们需要访问FormGroup您推送到数组上的每个模型,然后访问其中的命名控件:

<span formGroupName="{{i}}">
  <input type="checkbox" formControlName="{{category.name}}">
  {{category.name}}
</span>

We'll also need to tweak how we're pushing values so that the name is set uniquely instead of always set as "name":

我们还需要调整我们如何推送值,以便名称设置唯一而不是始终设置为"name"

let fg = new FormGroup({});
fg.addControl(this.categories[i].name, new FormControl(false))
allCategories.push(fg)

Here's a plunker to demo it: http://plnkr.co/edit/OTiqwr1oCb8uEThQyDHx?p=preview

这是一个演示它的plunker:http://plnkr.co/edit/OTiqwr1oCb8uEThQyDHx?p=preview

回答by ranakrunal9

I think because of same name categoriesof your component variable and form group control you are getting error. Check it by making below change in your component and form HTML :

我认为由于categories您的组件变量和表单组控件的名称相同,您会收到错误消息。通过在您的组件和表单 HTML 中进行以下更改来检查它:

You can check FormArrayName directivefor more reference.

您可以查看FormArrayName 指令以获取更多参考。

//Component

//零件

updateDetailsForm: FormGroup;
private allCategories : Category[] = []

constructor(private router: Router,
            private ss : SearchService,
            private formBuilder: FormBuilder) {
  this.initForm() // before the categories loaded
  this.ss.getAllCategories().subscribe(
    data => {
      this.allCategories = data
      this.initForm() // refresh the form with categories
    }
  )
}
initForm() {
  let allCategories: FormArray = new FormArray([]);
  for (let i = 0; i < this.allCategories.length; i++) {
    allCategories.push(new FormControl());
  }
  this.updateDetailsForm = this.formBuilder.group({
    'image' : [''],
    'categories': allCategories
  })
}

// Form HTML

// 表单 HTML

<div formArrayName="categories">
   <div class="form-group" *ngFor="let category of categories.controls; let i = index">
      <label>
        <input type="checkbox" formControlName="i">
          {?{allCategories[i].name}}
      </label>
   </div>
</div>