【问题标题】:Angular 6 - How do I Clone/Duplicate a div in typescript?Angular 6 - 如何在打字稿中克隆/复制 div?
【发布时间】:2018-06-06 02:51:37
【问题描述】:

我正在开展一个项目,该项目涉及提供有关车辆部件的信息。每个组件都有一组描述性字段。我有一个“添加另一个组件”按钮,需要创建一个具有相同字段的相同 div 容器。当然,克隆的父 div 将需要不同的 ID。例如:

在组件html文件中:

<div id="component-outer">
    <div class="component-inner">
         Component Content....
    </div>
</div>
<button type="button" (click)="clone()">Add Another Component</div>

在组件ts文件中:

export class AppComponent {
    clone(){
         Need to clone #component-outer div and append below the last instance 
         of that div, then append the div name on the cloned element.
    }
}

我习惯于使用 javascript/jQuery 来克隆元素,但是很难找到最好的方法来准确地在 Angular 中完成我想要完成的工作。克隆是正确的方法吗?

【问题讨论】:

  • 您应该在模型中克隆一个项目,并将您的 HTML 绑定到一个列表。你不应该直接在 Angular 应用程序中操作 DOM。

标签: javascript angular typescript clone


【解决方案1】:

您可以使用*ngFor 为数组中的每个项目创建 DOM 元素。

<div id="component-outer">
    <div *ngFor="let item of items" class="component-inner">
         Component Content....
    </div>
</div>
<button type="button" (click)="append()">Add Another Component</div>

export class AppComponent {
     public items: any[];

     public append() {
          this.items.push({
              // values depend on what an item is
          });
     }
}

这在 first 教程的 first 章节的文档中有所介绍。

https://angular.io/guide/displaying-data#showing-an-array-property-with-ngfor

【讨论】:

    猜你喜欢
    • 2020-03-27
    • 2015-03-24
    • 1970-01-01
    • 2019-02-23
    • 2018-02-24
    • 2019-03-01
    • 1970-01-01
    • 2021-09-13
    相关资源
    最近更新 更多