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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With