【问题标题】:How to add nested fields in IONIC2/ Angular2 form with seperate add button如何使用单独的添加按钮在 IONIC/Angular 2 表单中添加嵌套字段
【发布时间】:2018-01-11 22:13:33
【问题描述】:

我需要在表单中添加嵌套字段。我完全按照本教程http://brophy.org/post/nested-reactive-forms-in-angular2/

虽然每件事对我来说都很好,除了我需要添加按钮与每个孩子一起使用,并单击在他们之间添加的孩子。

例如:如果有

child1 add-btn child2 add-btn child3 add-btn child4 add-btn

现在如果单击 child2 的 add-btn,则应在 child2 之后插入新字段。

我尝试过:在 for 循环中使用标签,如下所示,它显示了添加按钮,但在单击该新字段时,总是在末尾插入这是不希望的。

 <a href="" (click)="addChild()">
        Add Child
    </a>

我的想法: 我可以在 add 函数中传递 id,如下所示,然后插入到该索引处的数组中。但不幸的是,不知道如何做到这一点。

(click)="addChild(idx)"; 

希望很清楚。请让我知道我是否可以使用这种方法实现预期。提前致谢。

回答:毕竟我关注了https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2 .. 并通过 -

control.insert(i+1, addCtrl);

【问题讨论】:

    标签: javascript typescript ionic2 angular2-template angular2-forms


    【解决方案1】:

    毕竟我关注https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2 .. 并通过 -

    control.insert(i+1, addCtrl);
    

    希望对某人有所帮助。

    【讨论】:

      【解决方案2】:

      只需像这样存储 ngFor 循环的索引:

      <div *ngFor="let item of items; let i = index;">
          {{item.name}}
          <a href="" (click)="addChild(i)">
              Add Child
          </a>
      </div>
      

      变量 i 现在将存储每个项目的索引,并且在按钮单击事件时,项目的索引将作为参数发送到 addChild() 方法。然后,您可以在组件中的该位置添加一个新项目:

      export class FieldsComponent {
      
          items: Array<any> = [
              {name: 'item1'}, 
              {name: 'item2'}, 
              {name: 'item3'}, 
              {name: 'item4'}
          ];
      
          addChild(index: number): void {
              //Insert after the index of the clicked button
              items.splice(index + 1, 0, {name: 'Added item'});
          }
      }
      

      【讨论】:

      • 感谢您的回答。但在我的情况下,插入功能可以完美地工作为: control.insert(i+1, addCtrl);
      猜你喜欢
      • 2017-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-24
      相关资源
      最近更新 更多