Home > Software design >  Typescript / Angular | Removing First Object of an Array
Typescript / Angular | Removing First Object of an Array

Time:07-12

my Button in .html

  <button (click)="deleteFirst()">Delete First</button>

My array and function in .ts:

persons = [ 
    {surname: "Tom", lastname: "Brown"},
    {surname: "Ben", lastname: "Smith"},
    {surname: "Alan", lastname: "Black"},
    {surname: "Nick", lastname: "White"}]

// this does not work
deleteFirst = () => {
    this.persons[0].shift;
  }

How can I remove the first / last Object of an array?

CodePudding user response:

shift method does not work that way. You need to call it, preferably on an Array.

Your version should be like this, if you are ok with mutating source Array:

deleteFirst = () => {
  this.persons.shift();
}
  • Related