How to Implement the Play/Pause Button in an Angular Application

I'm working on adding a show/hide feature to the play and pause buttons for a list of tracks in Angular 7. I had some success with Angular animation initially, but encountered an issue where all buttons in my list would change state instead of just one. I also attempted to use ngClass without achieving the desired result.

Here is my latest attempt. Any assistance would be greatly appreciated.

<mat-card class="track-box" *ngFor="let track of tracks" cdkDrag>
      <div class="custom-placeholder" *cdkDragPlaceholder></div>

      <span>

        <mat-icon  
        class="play-button md-48"
        [ngClass]="{'show' : track === selectedTrack}"
        (click)="toggle(track)"
        > play_circle_outline</mat-icon>

        <mat-icon 
        class="pause-button md-48" 
        [class.selected2]="track === selectedTrack"
        (click)="toggle(track)"
        >pause_circle_outline</mat-icon>  

      </span>

Answer №1

In response to @Tomato's answer, I have a different perspective as mentioned in my comment.

Instead of using Angular's NgClass, which is similar to ngIf, consider this alternative approach. With ngIf, you create 2 components, toggling between them repeatedly. This may not be the most efficient coding practice.

On the other hand, ngClass allows for the creation of one component and two separate SCSS classes for that component. When a specific condition is met, one SCSS class is applied accordingly.

  • HTML File

      <span>
        <button
        class="play-pause-button"
        [ngClass]="toggle(track)"></button>
      </span>
    

  • TS File

export class Component {

    let isPlay = false;

    public toggle(track: string) {
        this.isPlay = !this.isPlay;
        this.isPlay ? return 'play-button'; : return 'pause-button'
    }

}

By utilizing the toggle() function, you can dynamically assign a corresponding SCSS class based on the button's current state.

Answer №2

Utilizing ngClass Directive

To switch the displayed button icon, you can utilize the ngClass directive like this:

<mat-card class="track-box" *ngFor="let track of tracks" cdkDrag>
      <div class="custom-placeholder" *cdkDragPlaceholder></div>

      <span>
        <mat-icon  
        class="md-48"
        [ngClass]="{'play-button' : track != selectedTrack,
            'pause-button' : track === selectedTrack}"
        (click)="toggle(track)">Some output here</mat-icon>

      </span>
</mat-card>

Employing ngIf Directive

You might consider using the ngIf directive (documentation) to toggle the visibility of the buttons. However, as noted by Chris, this approach could lead to performance issues with a large list.

<mat-card class="track-box" *ngFor="let track of tracks" cdkDrag>
      <div class="custom-placeholder" *cdkDragPlaceholder></div>

      <span>
        <mat-icon  
        class="play-button md-48"
        *ngIf="track != selectedTrack"
        (click)="toggle(track)">play_circle_outline</mat-icon>

        <mat-icon 
        class="pause-button md-48" 
        *ngIf="track === selectedTrack"
        (click)="toggle(track)">pause_circle_outline</mat-icon>  

      </span>
</mat-card>

If the selectedTrack is not equal to the track, display the play-button; otherwise, show the pause-button.

You can also utilize the if-else-block syntax for this purpose (as shown in the documentation):

<div *ngIf="condition; else elseBlock">Content to render when condition is true.</div>
<ng-template #elseBlock>Content to render when condition is false.</ng-template>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The JSON input abruptly reached its end during parsing at an unexpected moment

When attempting to write to an existing JSON file, I discovered that I need to read the file, insert the new item, and then write it again. This process usually works fine, but occasionally I encounter an error message that reads, "Unexpected end of JSON ...

Enhancing an image with a hover-activated overlay

I'm trying to enhance the setup of my page with three images in columns by adding an extra overlay on top of the main image but beneath the hover effects. However, I seem to be encountering some difficulties while working on it. Take a look at my cod ...

Comparing Angular 2 Components and AngularJS Directives: What Sets

Are there any parallels or distinctions between an angular2 component and an AngularJS directive? It seems that these two share similar functionalities in the angular2 component and AngularJS directive. Additionally, angular2 also incorporates a directive ...

What is the best way to conceal a Material UI button with CSS?

For my TODO react app, I am using a Material UI button. My goal is to create a form with an input field and a submit button, but I want the submit button to be invisible so that users think the form submits when they press the "Return" key. import { Tex ...

Develop a unique splitter code that utilizes pure javascript and css, allowing users to drag and drop with precision

I am facing an issue with setting the cursor above my drop panel, as it results in a flicker effect. How can I set the cursor for my example to work properly? I have tried multiple different approaches to make this work. Although I am using the provided ...

Automatically save form controls with formControlName in Nativescript

I have placed a TextField in my .html file <TextField class="textfield" row="0" col="1" formControlName="powersupplyid" [text]='myipdevice'> </TextField> I am looking for a way to automatically save the value when 'myipdevice&a ...

Component in Next.js fetching data from an external API

I am attempting to generate cards dynamically with content fetched from an API. Unfortunately, I have been unsuccessful in finding a method that works during website rendering. My goal is to pass the "packages" as properties to the component within the div ...

Upgrading from Angular 10 to 13 resulted in an error that required adding 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas'. Although this fix was implemented, the issue still persists and the application remains broken

Here are a few examples of errors: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Error occurred in the template of component ShochatactivestreamviewShellComponent. Error: src/app/money_makers/shochat_guts/shochat_content_creato ...

The continuation of unraveling the mystery of utilizing `overflow-y:scroll` in a horizontal slider

As a beginner, I realized too late that adding code in comments is not an option. Consequently, I decided to create a new question and ask for your assistance once again. To optimize the use of space, I have implemented bxSlider with fixed dimensions (wid ...

Adjust the width of xAxis[0] and xAxis[1] in Highcharts to their default values

Hi there, I need some help with Highcharts. Is it possible to adjust the width of xAxis[0] and xAxis[1] as well as reset the offset of xAxis[1] at runtime? I have a chart with two x-axes that need to be resized to fit different sized divs. You can see an ...

Utilizing Express, Request, and Node.js to manage GET requests in typescript

I'm struggling with using Express and Request in my project. Despite my efforts, the response body always returns as "undefined" when I try to get JSON data from the server. In my server.js file, this is the code snippet I have been working on: impo ...

Having trouble finding a solution to prevent code from automatically adding a class in jQuery/JavaScript?

I am currently in the process of customizing the FlexNav Plugin. I have made a modification to allow sub-menus to open on click instead of hover. However, a new issue has arisen where it requires two clicks to open a submenu. Upon investigation, I have i ...

Creating a flexible parent tag for grouping child elements using Angular 2

My Objective I am determined to develop an Angular 2 button component that can dynamically render as either an <a /> tag or an <input /> tag based on the value of a property called type. Furthermore, this button component should be able to acc ...

Exponential calculator in Javascript

I'm working on a basic calculator project using html5, css3 and javascript. However, I've run into an issue with the exponent button not functioning properly. Here's my code snippet: <html> <head> <meta charset = "utf-8" ...

Craft a dynamic countdown timer that blinks using CSS

I am attempting to design a blinking countdown timer that starts at 5 seconds and disappears when it reaches 0. CSS: .blinky { transition: 1s opacity; -moz-transition: 1s opacity; -webkit-transition: 1s opacity; } HTML: <div id="count ...

Having trouble with the Ng multiselect dropdown displaying empty options?

I'm currently facing a challenge in adding a multiselect dropdown feature to my project. Below is the code I have been working on: HTML <ng-multiselect-dropdown [settings]="searchSettings" [data]="dummyList" multiple> </n ...

What steps can be taken to make sure padding impacts all lines, not just the first one?

I have added padding to a span of text using Bootstrap. However, the issue arises when the text goes to the next line using < br > - the padding for that line and beyond disappears. Here is the specific code causing this problem: <div class="col ...

How can I retrieve the value of the mdslider in Angular 2?

I am seeking a solution to display the value of a matSlider in an input field. <div class="col-lg-4 col-md-4 col-sm-12"> <mat-slider class="example-full-width" [max]="" [min]="min" [step]="step" [thumb-label]="thumbLabel" ...

To grab a specific CSS attribute from a stylesheet using JavaScript

I am looking for a way to extract the value from a CSS file using a JavaScript function. Take a look at my code snippet below: HTML file -> <link rel="stylesheet" type="text/css" href="test_css.css" /> <script type="text/javascript ...

Image that adjusts its size according to the device screen width while

My goal is to create responsive images with a fixed height. Below is the HTML code I am using: <div class="col-md-6"> <div class="img"> <img src="http://image.noelshack.com/fichiers/2016/16/1461065658-b-v-s.jpg"> </div&g ...