Eddie Taliaferro
Eddie Taliaferro

Reputation: 288

*ngFor... targeting a specific element in the loop (with an event)

So this is the situation: I have a list of objects being generated from a ngFor loop. I am trying to click on a single element, and change the contents of the markup for that particular element. When a user clicks the element, I want the track number to display "playing". The way I have it programmed, it applies the change to every element in the loop.

HTML:

<li class="song-block"
      *ngFor='let song of songsToDisplay'
      (click)="getSong(song)">
    <div (click)="play()" class="song-card">
      <p  *ngIf="!isPlaying"class="song-number">{{song.tracknumber}}</p>
      <p *ngIf="isPlaying"class="song-number">Playing</p>
      <p class="song-name">{{song.name}}</p>
      <p class="song-length">{{song.length}}</p>
      <svg class="explicit"
          *ngIf="albumToDisplay.isExplicit === 'true'"
          viewBox="0 0 24 24"
          preserveAspectRatio="xMidYMid meet"
          focusable="false">
            <g class="style-scope iron-icon">
              <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-4 6h-4v2h4v2h-4v2h4v2H9V7h6v2z"></path></g></svg>
    </div>
  </li>

TypeScript:

isPlaying: boolean = false; 

play(){
    this.isPlaying = true;
    console.log(this.isPlaying)
  }

Here is a visual of the app: https://i.sstatic.net/Onfwz.png

How can I target just one specific element within that loop? I feel like I am missing something incredibly simple here that I should not be missing.

Upvotes: 4

Views: 1524

Answers (1)

Pengyy
Pengyy

Reputation: 38161

You should add isPlaying property to each item of songsToDisplay, and change target song isPlaying to true after target song is clicked. Then display each song's playing status based on it's own isPlaying property.

Template:

<div (click)="play(song)" class="song-card">
  <p *ngIf="!song.isPlaying"class="song-number">{{song.tracknumber}}</p>
  <p *ngIf="song.isPlaying"class="song-number">Playing</p>
  ...
</div>

TS:

play(song){
  song.isPlaying = true;
  //console.log(this.isPlaying)
}

BTW, remember to roll song.isPlaying back to false when the song meets it's end.

Upvotes: 4

Related Questions