简体   繁体   English

如何获取ngFor数组的DOM元素?

[英]How can I get the DOM element of a ngFor array?

How can I get the actual element of a ngFor, so that I can work with it in the Component.ts 如何获取ngFor的实际元素,以便可以在Component.ts中使用它

Example: 例:

//.html
<div *ngFor="let element of elements">
      <md-card>{{element}}
           <button (click)="delete()">Delete</button>
     </md-card>
</div>

//.ts
   public delete() {
        mydata.delete(this.element)    //how to delete the actual element?
    }

Maintaining Index of Element 元素维持指数

You can maintain the index in loop and pass to the method. 您可以保持索引处于循环状态并传递给方法。

//.html
<div *ngFor="let element of elements; let i = index;">
      <md-card>{{element}}
           <button (click)="delete(i)">Delete</button>
     </md-card>
</div>

//.ts
   public delete(index:number) {
      // if your elements is an array, you can use splice.
     elements.splice(index, 1);
    }

Passing The Full Element 传递全部要素

If your data structure has a way to delete based on an element being passed to it. 如果您的数据结构有一种基于传递给它的元素删除的方法。 Arrays don't have a delete method that takes an object, you have to splice. 数组没有带对象的delete方法,必须进行拼接。 You can just pass the object like this 您可以像这样传递对象

//.html
<div *ngFor="let element of elements">
      <md-card>{{element}}
           <button (click)="delete(element)">Delete</button>
     </md-card>
</div>

//.ts
   public delete(element:ElementType) {
        mydata.delete(element)    //how to delete the actual element?
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM