MANZARBEITIA
MANZARBEITIA

Reputation: 123

Problems deleting an element from a object array in typescript

I'm trying to delete permanently an element of this object array:

 playlists: object[] = [
        { title: 'Ejemplo 1', songs: [ 'cancion1', 'cancion2', 'cancion3'] },
        { title: 'Ejemplo 2', songs: [ 'cancion1', 'cancion2', 'cancion3' ] }
  ];

I've tried with the splice method but it when I refresh the webpage it appears again:

deletePlaylist( index: number){

      this.playlists.splice(index, 1);

  }

Here from where does index come from:

<div *ngFor="let playlist of playlists; let i = index" class="card text-white bg-success m-3 animated fadeIn" style="max-width: 18rem;">
        <div class="card-header">{{ playlist.title }}</div>
        <div class="card-body">
            <h5 class="card-title">{{ playlist.title }}</h5>
            <ul *ngFor="let song of playlist.songs" class="card-text">
                <li>{{ song }}</li>
            </ul>
            <div class="row">
                <div class="col text-right">
                    <button (click) = "deletePlaylist( i )" class="btn btn-danger text-left" ><i class="fas fa-trash"></i></button>
                </div>
            </div>
        </div>
    </div>

Any ideas?

Upvotes: 0

Views: 56

Answers (2)

i.karayel
i.karayel

Reputation: 4875

You can save to local storage or session storage. Example

localStorage.setItem(key, JSON.stringify(val));

and you can get with:

var myObject = JSON.parse(localStorage.getItem('key'));

see

Upvotes: 0

G&#233;r&#244;me Grignon
G&#233;r&#244;me Grignon

Reputation: 4228

By refreshing your webpage, you loose any current state of your application. The component is once again created with the playlists array containing 2 items. If you want to keep track of data changes when refreshing your webpage, you need to persist it.

Upvotes: 1

Related Questions