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

When using EmotionJS with TypeScript, the theme type is not properly passed to props when using styled components

CustomEmotions.d.ts import '@emotion/react'; declare module '@emotion/react' { export interface Theme { colors: { primaryColor: string; accentColor: string; }; } } MainApp.tsx import { ...

Dealing with asynchronous tasks in JavaScript

I am currently delving into the world of Node development and struggling to grasp the asynchronous nature of JavaScript and Node.js. My project involves creating a microservices backend web server using Express in the gateway service, which then translates ...

Error message: Nextjs encounters hydration issue only in the production environment

I've been facing this issue for hours now. I deployed my Next.js application on Vercel and encountered numerous hydration errors there. Interestingly, in my local development environment, I don't experience any errors at all. I came across sugge ...

Include a Custom Button with an Optional Event Handler

I've created a customized material-ui button component: type ButtonProps = { disabled: boolean; text: string }; export function CustomButton({ disabled, text }: ButtonProps) { return ( <Button type="submit" disabled={disabled} ...

Enforce a mandatory selection in a group of checkboxes depending on the input value in a

I have a new challenge with a form that includes a group of checkboxes and a textbox. I need to make the checkboxes mandatory based on the value entered in the textbox. I am looking for a way to declare the checkbox group similar to how I did it in the p ...

The integration of the jQuery library within the server side of a Google Apps Container Bound Script

Can the jQuery library be utilized server-side in a Google Apps Script that is Container Bound to a Doc or Sheet? If so, what steps should be taken? In a previous inquiry on Stack Overflow, I sought guidance on incorporating jQuery into a container-bound ...

The beauty of crafting intricate forms with Angular's reactive nested

In my Angular project, I am exploring the concept of nesting multiple reactive forms within different components. For instance, I have a component called NameDescComponent that includes a form with two inputs - one for name and one for description, along ...

Unlock the canGoBack feature in your Ionic 5 app with these simple steps!

I'm currently working on implementing a back button in my Ionic app, but I am running into an issue. I need to hide the back button when it's at the root level, which is dynamic and can change based on the flow of the app. I came across some code ...

What are the steps to integrate my server-side PHP code into this form wizard?

Having created a straightforward 3 step form wizard for registration, I encountered an issue at the last stage when users click on submit. The desired action is to direct users to the PHP code that has been written. Update: Despite updating the HTML code ...

Error: Trying to call an undefined function

Having trouble with an error on this line: $("#register-form").validate. Can anyone offer assistance? Furthermore, if I write this script, how should I incorporate it into the form? Will it function without being called? <script type="text/javascript ...

Tips for ensuring Opera browser compatibility with buttons using the CSS background image property

Is there a way to make background images work on buttons in Opera web browser using CSS? I've tried using the background image property, but it doesn't show up when I use Opera. Strangely enough, it works fine in Firefox. However, I have noticed ...

Creating a comparison display using ng-repeat

I have a JSON file that contains revision and history information about a modified entity, including its old and new values. The diff is generated using the jsondiffpatch library and I have parsed it further to create the final JSON format for rendering. ...

What is the best way to remove a specific HTML section using a JavaScript function?

I am struggling to figure out how to remove a specific HTML section using a button that is contained within the section itself. The section I want to delete was initially added by clicking a different button. Although I can successfully add a new section ...

What is the best way to adjust a fixed-width table to completely fill the width of a smartphone browser?

In an ancient web application, the design was primarily constructed using rigid tables: <div class="main"> <table width="520" border="0" cellspacing="0" cellpadding="0"> <tr> <td>...</td> </ ...

Aurelia: The passing down of views and view-models

In the process of developing an Aurelia app, I am tasked with creating functionality that allows users to display various lists for different resources. These lists share common features such as a toolbar with search and refresh capabilities, along with a ...

Having difficulty executing the npm test command for my Angular 2 application

I am currently working on an Angular 2 application, and I am fairly new to it. I have set it up with Cordova app and run it through npm. The app starts without any errors and runs smoothly. However, when I try to run the tests using node (i.e., npm test), ...

Identifying the class name of SVGAnimatedString

While working on creating an SVG map, I encountered an issue where the functions triggered by hovering over 'g' elements were not functioning as expected. In order to troubleshoot this problem, I decided to check for any issues with the class nam ...

Spread an all-encompassing category across a collection

What is the method in TypeScript to "spread" a generic type across a union? type Box<T> = { content: T }; type Boxes<string | number> = Box<string> | Box<number>; (Given that we are aware of when to use Boxes versus Box) ...

Creating a dynamic 2x2 grid with centered responsiveness in Angular Ionic framework

I'm having trouble achieving a 2 x 2 grid that is centered on my screen. The code snippet below shows what I have so far in the HTML file. Just to provide some context, this project is meant for a native mobile application. <ion-header> <i ...

Accessing loop variables in Render and passing them into componentDidMount() in ReactJS to include as a query parameter in an API call

Within the render function, I am using a loop to rotate an array of coordinates in order to position markers on a map. {coords.map(({ lat, lng }, index) => (code goes here and so on))} I intend to replace query parameters with the variable generated f ...