在 Angular 中以动态反应形式添加项目 [英] Add item in dynamic reactive form in Angular

查看:25
本文介绍了在 Angular 中以动态反应形式添加项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Angular 5 中构建一个嵌套的反应式表单.我能够在一个级别推送项目,但无法在第二级推送项目.

ngOnInit() {this.orderForm = this.formBuilder.group({顾客姓名: '',电子邮件: '',项目:this.formBuilder.array([this.createItem()])});}createItem(): FormGroup {返回 this.formBuilder.group({名称:'a',描述: 'b',价格:'c',//subItems: this.formBuilder.array([this.createSubItem()])});}//createSubItem(): FormGroup {//返回 this.formBuilder.group({//子名:'abc'//});//}添加项目():无效{this.items = this.orderForm.get('items') as FormArray;//this.subItems = this.items.get('subItems') as FormArray;//this.subItems.push(this.createSubItem());this.items.push(this.createItem());}

在上面的代码中,未注释的代码与 push 一起工作正常.我在项目中有更多的子项目,注释代码是我试图实现的代码,但它不起作用.

任何机构都可以告诉我如何实现这一目标吗?

对于未注释的代码,我像这样在 html 中显示数据,并且运行良好.如果任何正文在代码级别有解决方案,还请告诉我如何更新嵌套项的 html.

<div formArrayName="items" *ngFor="let item of orderForm.get('items').controls; let i = index;"><div [formGroupName]="i"><input formControlName="name" placeholder="项目名称"><input formControlName="description" placeholder="项目描述"><input formControlName="price" placeholder="商品价格">

<input type="button" value="sldkj" (click)="addItem()"></表单>

解决方案:

首先,我设法预先填充了这样的值.

 obj = [{'name': "umair",'描述': "desc1",'子项目':[{'子名':'值'},{'子名':'值2'},{'子名':'值3'}]},{'name': "阿里",'描述': "desc2",'子项目':[{'子名':'value4'},{'子名':'值5'},{'子名':'值6'}]}]ngOnInit() {this.createForm(this.obj);console.log(this.orderForm);}创建窗体(对象){var arr = [];for (var i = 0; i < obj.length; i++) {arr.push(this.createItem(obj[i]));}this.orderForm = this.formBuilder.group({项目:this.formBuilder.array(arr)});}createItem(obj): FormGroup {var subArr = [];for (var i = 0; i < obj.subItems.length; i++) {subArr.push(this.createSubItem(obj.subItems[i]));}返回 this.formBuilder.group({名称:obj.name,描述:obj.description,子项:this.formBuilder.array(subArr)});}createSubItem(subItem): FormGroup {返回 this.formBuilder.group({子名称:subItem.subname});}

在下面的标记"答案中获得帮助后,我设法添加了子项并在 html 中填充,如下所示.

 <!-- <label>{{item.get('name').value}}</label>--><div formArrayName="items" *ngFor="let item of orderForm.controls.items.controls; let i = index;"><div formGroupName="{{i}}"><!-- <label>{{item.get('name').value}}</label>--><input formControlName="name" placeholder="项目名称"><input formControlName="description" placeholder="项目描述"><input type="button" value="subAdd" (click)="addSubItems(i)"><div formArrayName="subItems" *ngFor="let subItem of item.controls.subItems.controls; let idx = index;"><div formGroupName="{{idx}}"><!-- <label>{{subItem.get('subname').value}}</label>--><input formControlName="subname" placeholder="项目名称">

</表单>

代码

addSubItems(_index: any): void {var a = this.orderForm['controls']['items']['controls'][_index] as FormGroup;this.subItems = a.get('subItems') as FormArray;var newSubItem = {'子名':'值6'}this.subItems.push(this.createSubItem(newSubItem));}

解决方案

所以首先让我们了解你的工作.

您在 formarray 中创建一个 formarray.所以这意味着它有两个循环.所以你必须 *ngFor 第一个和 *ngFor 第二个.最后,这意味着您的项目有一个 index i 和子项目的 j.然后你可以添加 addSubItems(i) 来推送你的子项.

您的 html 应如下所示:

<div formArrayName="items"><div *ngFor="let 数组 orderForm.controls.items.controls; let i = index;"><div formGroupName="{{i}}"><input formControlName="name" placeholder="项目名称"><input formControlName="description" placeholder="项目描述"><input formControlName="price" placeholder="商品价格"><input type="button" value="subAdd" (click)="addSubItems(i)"><-- 这里是您的按钮--><div formArrayName="subItems"><div *ngFor="let item of arrays.controls.subItems.controls; let j = index;"><div formGroupName="{{j}}"><input formControlName="subname" placeholder="Item subname">

您的 addSubItems 应该类似于:

 addSubItems(_index: any): void {this.item = this.orderForm['controls']['items']['controls'][_index] as FormGroup;this.subItems = this.item.get('subItems') as FormArray;this.subItems.push(this.createSubItem());

I am trying to build a nested reactive form in Angular 5. I am able to push items at one level, but unable to push item at second level.

ngOnInit() {
 this.orderForm = this.formBuilder.group({
  customerName: '',
  email: '',
  items: this.formBuilder.array([this.createItem()])
});
}

 createItem(): FormGroup {
    return this.formBuilder.group({
      name: 'a',
      description: 'b',
      price: 'c',
      //subItems: this.formBuilder.array([this.createSubItem()])
    });
 }

 //createSubItem(): FormGroup {
    //return this.formBuilder.group({
      //subname: 'abc'
    //});
 //}

 addItem(): void {
    this.items = this.orderForm.get('items') as FormArray;
    //this.subItems = this.items.get('subItems') as FormArray;
    //this.subItems.push(this.createSubItem());
    this.items.push(this.createItem());
 }

In the above code the uncommented code is working fine with push. I have further subItems inside items, and commented code is the one I am trying to achieve, but it is not working.

Can any body show me how to achieve this?

For uncommented code, I am showing data in html like this and it is working well. If any body have solution at code level, please also tell me how to update html for nested items as well.

<form [formGroup]="orderForm">
<div formArrayName="items" *ngFor="let item of orderForm.get('items').controls; let i = index;">
    <div [formGroupName]="i">
      <input formControlName="name" placeholder="Item name">
      <input formControlName="description" placeholder="Item description">
      <input formControlName="price" placeholder="Item price">
    </div>
  </div>
  <input type="button" value="sldkj" (click)="addItem()">
</form>

SOLUTION:

First of all I managed to pre-populate values like this.

 obj = [
    {
      'name': "umair",
      'description': "desc1",
      'subItems': [
        {
          'subname': 'value'
        },
        {
          'subname': 'value2'
        },
        {
          'subname': 'value3'
        }
      ]
    },
    {
      'name': "ali",
      'description': "desc2",
      'subItems': [
        {
          'subname': 'valu4'
        },
        {
          'subname': 'value5'
        },
        {
          'subname': 'value6'
        }
      ]
    }
  ]

  ngOnInit() {
    this.createForm(this.obj);
    console.log(this.orderForm);
  }

  createForm(obj) {
    var arr = [];
    for (var i = 0; i < obj.length; i++) {
      arr.push(this.createItem(obj[i]));
    }
    this.orderForm = this.formBuilder.group({
      items: this.formBuilder.array(arr)
    });
  }

  createItem(obj): FormGroup {
    var subArr = [];
    for (var i = 0; i < obj.subItems.length; i++) {
      subArr.push(this.createSubItem(obj.subItems[i]));
    }
    return this.formBuilder.group({
      name: obj.name,
      description: obj.description,
      subItems: this.formBuilder.array(subArr)
    });
  }

  createSubItem(subItem): FormGroup {
    return this.formBuilder.group({
      subname: subItem.subname
    });
  }

After help in 'marked' answer below, I managed to add subitem and populate in html like below.

 <form [formGroup]="orderForm">
  <!-- <label>{{item.get('name').value}}</label> -->
  <div formArrayName="items" *ngFor="let item of orderForm.controls.items.controls; let i = index;">
    <div formGroupName="{{i}}">
      <!-- <label>{{item.get('name').value}}</label> -->
      <input formControlName="name" placeholder="Item name">
      <input formControlName="description" placeholder="Item description">

      <input type="button" value="subAdd" (click)="addSubItems(i)">

      <div formArrayName="subItems" *ngFor="let subItem of item.controls.subItems.controls; let idx = index;">
        <div formGroupName="{{idx}}">
          <!-- <label>{{subItem.get('subname').value}}</label> -->
          <input formControlName="subname" placeholder="Item name">
        </div>
      </div>

    </div>
  </div>
</form>

code

addSubItems(_index: any): void {
    var a = this.orderForm['controls']['items']['controls'][_index] as FormGroup;
    this.subItems = a.get('subItems') as FormArray;
    var newSubItem = {
      'subname': 'value6'
    }
    this.subItems.push(this.createSubItem(newSubItem));
  }

解决方案

So first let start with understanding what you do.

You make a formarray in formarray. So this mean it have two loops. So you have to *ngFor the first and *ngFor the second. In the end this means you have an index i for your items and and j for your subItems. Then you can add addSubItems(i) for pushing your subItems.

Your html should look something like this:

<form [formGroup]="orderForm">
  <div formArrayName="items">
     <div *ngFor="let arrays of orderForm.controls.items.controls; let i = index;">
        <div formGroupName="{{i}}">
          <input formControlName="name" placeholder="Item name">
          <input formControlName="description" placeholder="Item description">
          <input formControlName="price" placeholder="Item price">
          <input type="button" value="subAdd" (click)="addSubItems(i)"> <-- here your button -->
          <div formArrayName="subItems">
             <div *ngFor="let item of arrays.controls.subItems.controls; let j = index;">
                <div formGroupName="{{j}}">
                   <input formControlName="subname" placeholder="Item subname">

Your addSubItems should look something like:

 addSubItems(_index: any): void {
    this.item = this.orderForm['controls']['items']['controls'][_index] as FormGroup;
    this.subItems = this.item.get('subItems') as FormArray;
    this.subItems.push(this.createSubItem());

这篇关于在 Angular 中以动态反应形式添加项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆