【问题标题】:how to duplicate child component template inside parent on click? (angular2)单击时如何在父级内复制子组件模板? (角度2)
【发布时间】:2017-04-06 00:23:09
【问题描述】:

我想知道是否可以通过单击按钮在父级 html 语法中复制子组件模板?

所以;

<child-component></child-component>

<span class="glyphicon glyphicon-plus" (click)="onDuplicate()"></span>

然后,一旦用户单击“+”字形图标并调用 onDuplicate() 函数,则父级具有:

 <child-component></child-component>
 <child-component></child-component>

 <span class="glyphicon glyphicon-plus" (click)="onDuplicate()"></span>

等等等等

我一直在寻找方法来做这样的事情,但找不到任何东西,所以我不知道从哪里开始。我希望有人能指出我正确的方向吗?

谢谢

【问题讨论】:

    标签: angular


    【解决方案1】:

    您可以在父模板中使用ngFor,并在父组件中定义属性。

    //父组件

    public childItems: any[] = [];
    
    public onDuplicate(){
      this.childItems.push(this.childItems.length);
    }
    

    //父模板

    <child-component *ngFor="let child of childItems"></child-component>
    
    <span class="glyphicon glyphicon-plus" (click)="onDuplicate()"></span>
    

    【讨论】:

      【解决方案2】:

      一个想法是让子组件包裹在*ngFor 中,然后在类实现上有一个计数器。然后单击将增加计数器(实际上是源数组)。像这样的:

      <div *ngFor="let cc of childrenCounter">
          <children-component></children-component>
      </div>
      
      <span class="glyphicon glyphicon-plus" (click)="onDuplicate()"></span>
      

      类具有:

      private childrenCounter: number[] = [];
      
      private onDuplicate(): void {
          this.childrenCounter.push(0); // just add any element
      }
      

      数组是一个丑陋的解决方案,而不是一个简单的计数器,但到目前为止it is necessary

      【讨论】:

        【解决方案3】:

        将您放入 *ngFor 指令并在您的函数 onDuplicate() 中增加循环变量(如果您有自定义对象,只需将您的对象推送到数组中)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-07-13
          • 1970-01-01
          • 2016-10-30
          • 1970-01-01
          • 2020-09-02
          • 2021-10-31
          • 1970-01-01
          相关资源
          最近更新 更多