WasiF
WasiF

Reputation: 28909

How to remove an element based on some property using typescript in angular

I want to remove an element from an array based on its any property that can be its key, name or email or something else it can be.

Html

<tr *ngFor="let person of persons;" (click)="remove(person.key)">
  <td>{{person.key}}</td>
  <td>{{person.name}}</td>
  <td>{{person.email}}</td>
</tr>

typescript

persons = [
{ key: 1, name: 'Mr.sohail', email: '[email protected]' },
{ key: 2, name: 'Mr.Farhan', email: '[email protected]' },
{ key: 3, name: 'Mr.Fida', email: '[email protected]' },
{ key: 4, name: 'Mr.Liaqat', email: '[email protected]' },
{ key: 5, name: 'Mr.Abdullah', email: '[email protected]' },
{ key: 6, name: 'Mr.Ubaid', email: '[email protected]' },
{ key: 7, name: 'Mr.Wasif', email: '[email protected]' }
]

remove method to remove an element based on key property but it removes based on index.

remove(key) {
console.log(key);
this.data.persons.splice(key, 1);
}

Please let me know the required changes to apply

Thanks

Upvotes: 0

Views: 233

Answers (5)

Pankaj Parkar
Pankaj Parkar

Reputation: 136174

As you want to delete element from an collection based on dynamic key(assuming it should be unique). You could consider passing two parameter for your remove function, object and propName

<tr *ngFor="let person of persons;" (click)="remove(person,'key')">
  <td>{{person.key}}</td>
  <td>{{person.name}}</td>
  <td>{{person.email}}</td>
</tr>

remove(person, propName){
   this.persons = this.persons.filter(p => p[propName] !== person[propName])
}

Demo Here

Upvotes: 1

cyberpirate92
cyberpirate92

Reputation: 3176

 removeByPropertyName(propertyName: string, value: any): void {
    let indexToRemove = persons.findIndex(p => p[propertyName] === value);
    if (indexToRemove !== -1)
        this.remove(indexToRemove);
    else
        console.log('Not found!');
 }

To remove by key, you can use the method as

removeByPropertyName('key', 10);

To remove by name,

removeByPropertyName('name', 'somename');

Upvotes: 1

Michael Kang
Michael Kang

Reputation: 52867

Based on your use case, if you trying to remove an item when it is clicked, you can (and should) use the index. I see no reason to use a property.

Here is how I would remove an item base on an index:

<tr *ngFor="let person of persons; index as i" (click)="remove(i)">
  <td>{{person.key}}</td>
  <td>{{person.name}}</td>
  <td>{{person.email}}</td>
</tr>

remove(index) {
    this.data.persons.splice(index, 1);
}

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222700

What about using filter?

remove(key) {
console.log(key);
this.persons = this.persons.filter(t=>t.key != key);
}

Upvotes: 0

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41447

Use the filter function. Also, i think it should be this.persons not this.data.persons

remove(key) {
  console.log(key);
  this.persons= this.persons.filter(obj => obj.key !== key);

}

Upvotes: 0

Related Questions