wanjingy.github.io / hw8 / frontend / src / app / favorites / favorites.component.ts
favorites.component.ts
Raw
import { Component } from '@angular/core';

@Component({
  selector: 'app-favorites',
  templateUrl: './favorites.component.html',
  styleUrls: ['./favorites.component.css']
})
export class FavoritesComponent {
  favorites: any[] = [];
  noFav: boolean = false;
  ngOnInit(){
    this.loadFav();
  }

  loadFav(){
    const localFav = localStorage.getItem('favorites')
    if(localFav === null){
      this.noFav = true;
    }else{
      this.favorites = JSON.parse(localFav);
      if(this.favorites.length==0){
        this.noFav = true;
      }else{
        this.noFav = false;
      }
    }
  }

  deleteFav(eventID: string){
    for(var i=0; i<this.favorites.length; i++){
      if(this.favorites[i].id == eventID){
        this.favorites.splice(i, 1);
        break;
      }
    }
    localStorage.setItem('favorites', JSON.stringify(this.favorites));
    if(this.favorites.length==0){
      this.noFav = true;
    }
    alert('Removed from Favorites!');
  }
}