Tips for utilizing ng class within a loop

Having some trouble with my template that loops through a JSON file using json server. The issue I'm facing is related to correctly applying ng class when clicking on icons. Currently, when I click on an icon, it adds a SCSS class but applies it to all icons simultaneously. I'm trying to make it so that the SCSS class only applies to the specific icon I clicked on.

Any help is appreciated.

HTML

<div class="image-mosaic">
      <div class="card" *ngFor="let film of films">
            <img [src]="film.img" class="img-style">
            <div class="icon-style">
                <mat-icon (click)="addFavoris(film); $event.stopPropagation()" [ngClass]="{'rouge': film.favoris == true}">
                    favorite_border
                </mat-icon>
            </div>
        </div>
    </div>

TS

export class TemplateListComponent {
  public showFiller = false;
  @Input() public films: MovieListe[];
  @Output() public favoris = new EventEmitter();

  addFavoris(favoris: MovieListe) {
    this.showFiller = !this.showFiller;

    let t: MovieListe = { ...favoris };
    t.favoris = this.showFiller;

    this.favoris.emit(t);
  }
}

JSON

{
      "id": 1,
      "title": "Smile",
      "rating": 2,
      "releaseDate": "12/02/2010",
      "img": "assets/img/film.jpg",
      "favoris": true
    },

Answer №1

If you're looking to apply a new class to the element that was just clicked, follow these steps:

HTML

<div class="image-grid">
      <div class="item" *ngFor="let photo of photos">
            <img [src]="photo.url" class="photo-style">
            <div class="overlay">
                <mat-icon (click)="applyClass(icon)" #icon>
                    favorite_border
                </mat-icon>
            </div>
        </div>
    </div>

TS

export class GalleryComponent {
  public showFiller = false;
  @Input() public photos: Photo[];
  @Output() public favorites = new EventEmitter();

  public applyClass(element: MatIcon): void {
    element._elementRef.nativeElement.classList.add('new-class');
  }
  
}

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

CSS Flexbox: Achieving Perfect Alignment for a Responsive Hamburger Navbar

This is a specific inquiry that requires your attention To begin, kindly execute the code in fullscreen mode Inspect the code and adjust it to fit within a mobile width (there seems to be an issue with responsiveness) Next, open the hamburger menu As show ...

Ways to switch the visibility of a specific thumbnail

Our team has created a new app that showcases all the videos in our channel. Users can browse through thumbnails and click on one to view the related video, instead of viewing all videos at once. Angular Code $scope.isvideoPlaying = false; $scope.displ ...

Setting the default date format in dayjs: A quick guide

Is there a way for me to set the default date and time format to "YYYY-MM-DD HH:mm:ss" in order to avoid unnecessary repetitive code like the following: this.dayjs().startOf("year").format("YYYY-MM-DD HH:mm:ss") this.dayjs().format("YYYY-MM-DD HH:mm:ss") t ...

Tips to prevent modal impacts on underlying elements?

When I click on a button, a modal pops up. However, the background contents seem to spread out and sometimes scroll automatically when the modal appears. I have searched for a solution to this issue but have been unsuccessful. Can anyone please help me ide ...

Managing the output from a function: Tips and strategies

Below is the function I am currently working with: function kontrola(){ var jmeno = self.document.forms.newPassForm.user.value; $.get("checkMail.php?mail="+jmeno, function(data){ if(data=='1'){ alert('Tento ...

Leveraging Interface in Protractor Testing

As a newcomer to Typescript and Protractor, I have been working with reusable code in various classes. Instead of importing each library class separately into my test class, I am trying to find a way to import just one class or interface that will contai ...

Reaching out to the Edge: Enhancing the jQuery Slider Experience

Alright, I'm really excited about using this amazing slider. What I love most is the "free mode" feature that creates this stunning sliding effect. The size and number of slides are absolutely perfect for me. But there's just one small adjustment ...

When hovering over a circle in CSS with a background image to hide text, the shape becomes distorted

I am attempting to create a series of circles with background images and accompanying text displayed side by side. My goal is to have the image opacity change and the text disappear upon hovering over each circle. Additionally, I do not want underlines to ...

Display 'Div 1' and hide 'Div 2' when clicked, then reveal 'Div 2' and hide 'Div 1' when a different button is clicked

I need help figuring out how to make two separate buttons work. One button should display 'Div 1' and hide 'Div 2', while the other button should show 'Div 2' and hide 'Div 1' when clicked. My knowledge of jquery an ...

Sending jQuery variables to PHP

Is it possible to transfer a jQuery variable to a php file? Let's take a look at the code in my_js.js: function updates() { $.getJSON("php/fetch.php", function(data) { $.each(data.result, function(){ var s_id = this[& ...

What is the technique for rearranging columns to be at the top in Foundation for mobile devices?

On my desktop, I have a layout like this: [Column1 large-8] [Column2 large-4] For mobile view, I'd like it to be like this: [Column2 large-4] [Column1 large-8] Below is the code snippet I am working with: <div id="search-content" class="row ma ...

Tips for assigning a standard or custom value using JavaScript

What is the best way to automatically assign a value of 0 to my input field when the user leaves it blank? Should I use an if statement { } else { } ...

Ways to address observables in Angular in a manner similar to deferred objects

Transitioning from AngularJS to Angular has posed a challenge for me, especially when it comes to moving from promises to observables. Below is an example of my code in AngularJS: var deferred = $q.defer(), frame = document.createElement('newFrame ...

"I'm looking for a way to store and fetch TypeScript objects with PouchDB. Any suggestions on

As someone who is new to typescript and web development, I am eager to incorporate PouchDB into my typescript project to store my objects. Despite the lack of documentation, I am struggling to find the correct approach. I have created typescript objects t ...

Guide on incorporating arrays into an array using JavaScript

Is there a way to achieve the specified outcome in JavaScript? I attempted to find a method for it on MDN but was unsuccessful. let a, b let allNumbers = [] for (a = 10; a < 60; a = a + 10) { for (b = 1; b <= 3; b++) { allNumbers.push(a ...

How do I set up a 5 column layout for the home page and switch to a 4 column layout for category pages in Magento?

Is it possible to display 5 columns of products on the Magento home page and only show 4 columns in the category area, or is this a pre-set parameter that applies platform-wide? ...

How can I convert an HTML Div to CSS styling?

Currently, I am attempting to transform the following HTML code snippet into CSS. While I understand that you can utilize div in CSS, I am uncertain if it is possible to use an href with CSS. Here is the code in question: <div id="menubar1"> <a ...

Problem with Jquery show/hide feature only resolved after refreshing the page

I built a checkout page that consists of three fieldsets with unique IDs - 1, 2, and 3. I want the page to initially display only fieldset 1 while hiding fieldsets 2 and 3. Here is the jQuery code I used: $(document).ready(function(){ $("#1").show(); ...

Next.js fails to update the user interface (UI) when there is a change in

In my latest Next.js project, I am working on a feature that involves looping through an array of amenities. Each amenity is displayed in a div element that, when clicked, toggles the active property. The logic behind this functionality is handled by the ...

Encountering TS2322 error when defining a constructor in Angular 2 with ag-grid

Currently, I am following a tutorial I stumbled upon online titled Tutorial: Angular 2 Datatable with Sorting, Filtering and Resizable Columns. It appears to be the most straightforward guide to help me get started with the ag-grid library before delving d ...