Angular How to Remove Element from Array?

By Hardik Savani April 8, 2020 Category : Angular

Hi All,

Here, i will show you how to works angular remove element from array. We will use angular remove element from array by index. This article goes in detailed on angular delete element from array by value. We will use angular remove item from array by value.

We will remove item from array in angular 6, angular 7, angular 8, angular 9, angular 10, angular 11, angular 12 and angular 13 application.

I will give you four example of how to remove item from array in angular application. so it will help you easily. so let's see bellow example. let's see bellow example that will help you to delete item from array.

Angular Remove Element from Array by Index

import { Component } from '@angular/core';

@Component({

selector: 'my-app',

template: `<div>

<div *ngFor="let value of myArray; let myIndex=index;">

{{ value }} <button (click)="removeItem(myIndex)">Remove</button>

</div>

</div>`,

styleUrls: [ './app.component.css' ]

})

export class AppComponent {

name = 'Angular';

myArray = [1, 2, 3, 4, 5];

removeItem(index){

this.myArray.splice(index, 1);

}

}

Angular Remove Element from Array by Value

import { Component } from '@angular/core';

@Component({

selector: 'my-app',

template: `<div>

<div *ngFor="let value of myArray;">

{{ value }} <button (click)="removeItem(value)">Remove</button>

</div>

</div>`,

styleUrls: [ './app.component.css' ]

})

export class AppComponent {

name = 'Angular';

myArray = [1, 2, 3, 4, 5];

removeItem(value){

const index: number = this.myArray.indexOf(value);

this.myArray.splice(index, 1);

}

}

Angular Delete Item from Array by Object

import { Component } from '@angular/core';

@Component({

selector: 'my-app',

template: `<div>

<h1>angular remove element from array</h1>

<div *ngFor="let value of myArray;">

{{ value.id }}. {{ value.name }} <button (click)="removeItem(value)">Remove</button>

</div>

</div>`,

styleUrls: [ './app.component.css' ]

})

export class AppComponent {

name = 'Angular';

myArray = [

{ id:1, name:'Hardik'},

{ id:2, name:'Paresh'},

{ id:3, name:'Rakesh'},

{ id:3, name:'Mahesh'},

];

removeItem(obj){

this.myArray = this.myArray.filter(item => item !== obj);

}

}

Angular Delete Item from Array by Id

import { Component } from '@angular/core';

@Component({

selector: 'my-app',

template: `<div>

<h1>angular remove element from array</h1>

<div *ngFor="let value of myArray;">

{{ value.id }}. {{ value.name }} <button (click)="removeItem(value.id)">Remove</button>

</div>

</div>`,

styleUrls: [ './app.component.css' ]

})

export class AppComponent {

name = 'Angular';

myArray = [

{ id:1, name:'Hardik'},

{ id:2, name:'Paresh'},

{ id:3, name:'Rakesh'},

{ id:4, name:'Mahesh'},

];

removeItem(id){

this.myArray = this.myArray.filter(item => item.id !== id);

}

}

You can also see bellow layout:

I hope it can help you...