Streamline the ngClass conditions when using ngFor loops

My array consists of 5 string values: excited, happy, neutral, sad, angry.

To simplify my HTML and avoid repeating code for each value, I am utilizing ngClass and ngFor.

The challenge I'm facing is that the ngClass statement is quite lengthy, and I'm struggling to find a more concise way to write it. Is there a shorter approach to achieve the same result?

<mat-icon *ngFor="let smiley of smileys" svgIcon="emote_{{smiley}}" 
                [ngClass]="{ happy: smiley === 'happy', sad:  smiley === 'sad', neutral:  smiley === 'neutral', angry:  smiley === 'angry', excited:  smiley === 'excited'}" (click)="selected(smiley, $event)"></mat-icon>

I appreciate your assistance!

Answer №1

To include a smiley face, you just need to use the ngClass directive like this:

[ngClass]="smiley"

Answer №2

Enhance the content of the smileys array by incorporating a more sophisticated approach, wrap the specific class within each smiley element, and apply it when assigning to the resolve class.

Answer №3

Create a function called determineHappiness and put this part into it: happy: smiley === 'happy', sad: smiley === 'sad', neutral: smiley === 'neutral', angry: smiley === 'angry', excited: smiley === 'excited'. You can use a switch statement or if clauses inside the function to return the css-class-name based on the input.

After defining the function, you can call it in your HTML like this: [ngClass]="determineHappiness()

If you want more information on a similar issue, you can visit this link: check this one out

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

Encountered an issue trying to access undefined properties while reading 'PP'

I am trying to showcase the data retrieved from my JSON file. Here is a glimpse of the information stored in the JSON => Within DTA > PP , I am specifically interested in displaying the variable NOMFAMILLE. An error message has caught my attentio ...

Unable to retrieve title from view source with Angular 5 Universal

Looking for some assistance with setting up custom headers and footers in Angular 5. I have scoured the internet and tried various examples, but haven't had any luck. Link to my question on Stack Overflow about Header and Footer in Angular 5 I' ...

Error: No provider found for _HttpClient in the NullInjector context

Hello everyone, I am new to Angular and currently facing an issue that has me stuck. The error message I'm receiving is as follows: ERROR NullInjectorError: R3InjectorError(Standalone[_AppComponent])[_ApiCallServiceService -> _ApiCallServiceService ...

Tips for looping through a Set in TypeScript

What is the best way to loop through a set in TypeScript? Using for..of does not seem to work properly: 'Set<string>' is neither an array nor a string type Using .forEach is not ideal since it obscures the context of this. I would rather ...

What is the correct way to type this object conversion?

I'm trying to ensure type safety for a specific converting scenario. The goal is to map over the palette object and convert any entries to key-value pairs, similar to how tailwindcss handles color configurations. However, I am facing an issue where th ...

What steps can I take to prevent type errors from affecting my React app during hot-reloading with TypeScript?

Currently, I am facing a "compile" error while working on typescript + react. Below is the configuration I'm using. Is there a way to check types without compromising the build and hot-reload process? Can someone guide me on how to enforce compilation ...

What is the proper way to format data following the selection of a Material Datepicker?

I am using Angular material's datepicker with reactive forms: <mat-form-field > <mat-label>Start Date...</mat-label> <input formControlName="start" matInput [matDatepicker]="dateOrderDgeStart" /> <m ...

How to toggle code block visibility in Angular's ngOnInit() method

I'm currently analyzing different design patterns to optimize the number of REST calls when implementing a 'save while typing feature'. To provide a general overview, in my ngOnInit() function, I have included the following code snippet (wit ...

rxjs5 - the WebSocket constructor is missing

I can't seem to figure out this basic task. I'm attempting to create an Observable from rxjx/observable/dom/webSocket in RxJS5, but I'm not using typescript, or es6 modules... just plain 'ole good commonJS. Despite following the documen ...

Leveraging Bootstrap and jQueryUI in TypeScript: Merging with TypeScript Results in Duplicate Property 'tooltip' Error

In my .NET MVC project, I have successfully integrated jQueryUI and Bootstrap and imported types for TypeScript using npm "devDependencies": { "@types/jquery": "3.5.x", "@types/jqueryui": "1.12.x", ...

Guide to creating numerous separate subscriptions in angular 6

Can you explain the differences between flatMap(), switchmap(), and pipe()? Which one would be most suitable for the given scenario? I need to call the next method once both responses are received. this.jobService.getEditableText('admins', compar ...

How come TypeScript doesn't throw an error when I pass the incorrect type as a function parameter?

<template> <div class="app"> Greetings, {{ name }} <button @click="updateName('Jane')">Modify Name</button> </div> </template> <script lang="ts"> import { define ...

Guide to setting up Bootstrap in your Angular application

Currently attempting to incorporate bootstrap into my angular project. Here is the command I am inputting: npm install bootstrap jquery --save The response I receive is as follows: up to date, audited 1013 packages in 3s 92 packages are seeking fundin ...

Angular Error: Property 'map' is not found in type 'OperatorFunction'

Code: Using map and switchMap from 'rxjs/operators'. import { map, switchMap } from 'rxjs/operators'; Here is the canActivate code for route guard: canActivate(): Observable<boolean> { return this.auth.userObservable ...

Angular 5 - correcting the mismatched data type in binding function parameters for translations

I have a component that displays a list of items and triggers an action when a user clicks on a specific item. This is the basic functionality I am aiming for. Below is the HTML template I am using: template: ` <ul class="list" *ngFor="let item of it ...

Version 4.0 of Electron-React-Boilerplate has encountered an error: The property 'electron' is not recognized on the type 'Window & typeof globalThis'. Perhaps you meant to use 'Electron' instead?

I encountered an error while attempting to call the IPCrenderer using the built-in context bridge. The error message reads as follows: Property 'electron' does not exist on type 'Window & typeof globalThis'. Did you mean 'Elect ...

What is the best way to showcase 10 data points from a list of 100 in an Angular datatable?

Is there a way to display the first 10 values from a list of 100 using Angular DataTable? <tr *ngFor="let i of arr"> <td>{{i}}</td> </tr> ...

Troubleshooting: Angular 2 View not reflecting changes after array push

I have encountered an issue with my two child components. They are both meant to share data from a json file that I load using the http.get/subscribe method. Oddly enough, when I try to push new data into the array, it doesn't seem to update in the vi ...

Issue with reading the current length of an array object in a while loop in Angular 6

After successfully splitting an array into parts, I decided to add some filters to only include the items in the list that have an action status of (4). However, I encountered a problem where the while loop couldn't read the length of the array. This ...

Turning a JSON string into interpolation within an Angular application

I received a JSON response that looks like this: { someText: "Order in {000} 12pm PST for early shipping"; cutofftime : "10000000" } What is the most effective way to replace the '{000}' with the dynamic value stored in &quo ...