How can I get the actual element of a ngFor, so that I can work with it in the 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. 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?
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.