Setting a class for an HTML element within an ngFor loop

<div class="weather-app-wrapper" *ngIf="weather !== undefined">
    <div class="weather-wrapper" *ngFor="let forecast of weather.forecastDays">
        <div class="weather-card">
            <div class="forecast-icon" [ngClass]="{{forecast.condition}}"></div>
            <h1>{{forecast.tempMin}}º - {{forecast.tempMax}}º</h1>
            <p>{{forecast.day}}</p>
        </div>
    </div>
</div>

I am attempting to assign a class to an HTML element in this line:

<div class="forecast-icon" [ngClass]="{{forecast.condition}}"></div>
however, I am encountering an error. Is there a way to achieve this in HTML or does it need to be done in TypeScript? I am familiar with applying classes in static HTML, but I am unsure how to do so within a loop that generates HTML elements. The property forecast.condition contains a valid string, and the loop iterates 5 times without issue. Can you suggest a method to accomplish this?

For instance:

//forecast.condition = "sunny"
    <div class="forecast-icon"> 
should transform into 
    <div class="forecast-icon sunny"> 
on the rendered page

Below is the Forecast model:

export class ForecastDay {
    tempMin: number;
    tempMax: number;
    day: string;
    condition: string;
}

This is the encountered error:

Uncaught Error: Template parse errors: Parser Error: Got interpolation ({{}}) where expression was expected at column 0 in [{{forecast.condition}}] in ng:///AppModule/WeatherComponent.html@3:39 (" weather.forecastDays">
        <div class="weather-card">
            <div class="forecast-icon" [ERROR ->][ngClass]="{{forecast.condition}}"></div>
            <h1>{{forecast.tempMin}}º - {{forecast.tempMax"): ng:///AppModule/WeatherComponent.html@3:39 Parser Error: Unexpected token {, expected identifier, keyword, or string at column 2 in [{{forecast.condition}}] in ng:///AppModule/WeatherComponent.html@3:39 (" weather.forecastDays">
        <div class="weather-card">
            <div class="forecast-icon" [ERROR ->][ngClass]="{{forecast.condition}}"></div>
            <h1>{{forecast.tempMin}}º - {{forecast.tempMax"): ng:///AppModule/WeatherComponent.html@3:39 Parser Error: Missing expected : at column 21 in [{{forecast.condition}}] in ng:///AppModule/WeatherComponent.html@3:39 (" weather.forecastDays">
        <div class="weather-card">
            <div class="forecast-icon" [ERROR ->][ngClass]="{{forecast.condition}}"></div>
            <h1>{{forecast.tempMin}}º - {{forecast.tempMax"): ng:///AppModule/WeatherComponent.html@3:39 Parser Error: Unexpected token } at column 21 in [{{forecast.condition}}] in ng:///AppModule/WeatherComponent.html@3:39 (" weather.forecastDays">
        <div class="weather-card">
            <div class="forecast-icon" [ERROR ->][ngClass]="{{forecast.condition}}"></div>
            <h1>{{forecast.tempMin}}º - {{forecast.tempMax"): ng:///AppModule/WeatherComponent.html@3:39 Parser Error: Unexpected token '}' at column 22 in [{{forecast.condition}}] in ng:///AppModule/WeatherComponent.html@3:39 (" weather.forecastDays">
        <div class="weather-card">
            <div class="forecast-icon" [ERROR ->][ngClass]="{{forecast.condition}}"></div>

Answer №1

Interpolation isn't necessary when using [ngClass]. You can simply assign the class like so:

<div class="weather-icon" [ngClass]="weather.condition"></div>

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 a problem with Next JS API while trying to fetch data from the app directory

import { NextResponse } from "next/server"; export async function POST(request: Request) { const data = await request.json(); console.log(data); return NextResponse.json({ foo: "boo" }); } next version = "next": &quo ...

Unable to access global functions in Typescript

My current setup involves using cloudflare workers with miniflare. I have structured a bindings.d.ts file as follows: export interface Bindings { ENV: string MYSQL_URL: string JWT_SECRET: string JWT_ACCESS_EXPIRATION_MINUTES: number JWT_REFRESH_E ...

Updating a property in React by fetching data from API and storing it in the cache

Recently, I implemented nanoid to generate unique IDs for my NBA team stat tracker app. However, upon browser refresh, the fetch function generates new IDs for each team stored in the favorites list. This causes the app to fetch data again and assign a new ...

Confusing directions about parentheses for "this.fn.bind(this)(super.fn(...args)"

While reviewing a project, I came across code that can be simplified to: export abstract class Logger { private static log(level: LogLevels, ...args: Array<any>) {/**/} public error(...args: Array<any>): LogData { return Logger ...

Saving data from rowclicked event in ag-grid with Angular

My goal is to save the event data from the onRowClicked event in a Component member. This way, when the user clicks a button, the data can be deleted. However, I am facing an issue where the member variable becomes undefined when trying to access it in t ...

Encountering an issue with reading the property 'hasError' of undefined in reactive nested forms

I recently implemented reactive nested forms using Angular 8 along with Angular Material. Inside the component.ts file: this.dataForm = this.formBuilder.group({ name: [null, Validators.required], user: this.formBuilder.group({ firstnam ...

When implementing setInterval in React with TypeScript, remember to utilize the useRef hook

In my next.js app, I am implementing a basic animation. let flipInterval = useRef(); const startAnimation = () => { flipInterval.current = setInterval(() => { setIsFlipping((prevFlipping) => !prevFlipping); }, 10000); }; When tryin ...

How can you verify the correctness of imports in Typescript?

Is there a way to ensure the validity and usage of all imports during the build or linting phase in a Typescript based project? validity (checking for paths that lead to non-existent files) usage (detecting any unused imports) We recently encountered an ...

The parameter type 'OperatorFunction<User, void>' cannot be assigned to the parameter type 'OperatorFunction<Object, void>'

Hey there, I'm currently diving into Angular and trying to figure out how to work with API's. However, I've encountered a bit of a roadblock in my code when attempting to retrieve data from the key. Argument of type 'OperatorFunction&l ...

Is there an Angular 2 alternative to the JQuery .param() method?

Is there a similar function to $.param() from JQuery available for Angular2? While Angular 1 has a service like it, check out the Angular1 Equivalent I looked at the Angular 2 documentation here and they demonstrate a POST request with a JSON in the requ ...

What is the process for retrieving information from an observable array?

I am currently developing an application with a Python backend and Angular frontend. The main functionality of the app involves retrieving FIFA players from a MongoDB using the getLoyalPlayers function. Below is the snippet from the loyalty.component.ts f ...

Implement an interface with a specific number of properties in TypeScript

I am attempting to create a custom type that defines an object with a specific number of key-value pairs, where both the key and value are required to be numbers. Here is what I envision: type MatchResult = { [key: number]: number; [key: number]: numbe ...

What is the best way to prevent updating the state before the selection of the end date in a date range using react-datepicker?

Managing user input values in my application to render a chart has been a bit tricky. Users select a start date, an end date, and another parameter to generate the chart. The issue arises when users need to edit the dates using react-datepicker. When the s ...

Having difficulties launching plnkr for Angular 4

I have a plunger code here that is meant to display a child Component. Here is the HTML inside the child component: <div> <h3>I am the Child component</h3> </div> Take a look at the Plnkr code here. However, when I run ...

Combining different types and "currying" or partial application APIs in a unique way

Here is an interface that I am working with: interface IFactory<T> extends Function { (...args: any[]): (((...args: any[]) => T)|T); } After implementing the following code snippet, an error occurred: ts] Type '((...args: any[]) => ...

I am encountering a PeerInvalid error when attempting to launch myapp on an Android device using Ionic/Angular 4

For the past 3 days, I've been using Ionic and today I decided to try putting my application on my Android devices. However, I've encountered a problem... When I run: ionic cordova run android --device -l -debug I'm getting these errors th ...

Challenges arise when incorporating interfaces within a class structure

I created two interfaces outside of a class and then proceeded to implement them. However, when I tried to assign them to private properties of the class, something went wrong and I'm unable to pinpoint the issue. Can anyone offer assistance with thi ...

Various dateInput formats supported by mat-datepicker

I'm facing an issue while configuring two mat-datepickers with different date formats - "MM/YYYY" and "DD/MM/YYYY". I attempted to set the format for MM/YYYY in one module and the format for DD/MM/YYYY in the app module. Here is my first code snippet ...

How do you properly perform typechecking on a custom fetch function in ReactQuery? I'm encountering an error that states: "....is of an unknown type."

Currently, I am working with typescript + react-query and creating a custom fetch function. I am struggling to properly type this function and encountering a TypeScript error when attempting to use myQuery.error.message const locationQuery: QueryObserverRe ...

Enhance your Typescript code with a type guard that supports optional wrapped types

I haven't come across a question similar to this one before. My goal is to develop a type guard that can accurately determine the type of a specific variable. It's quite simple with a single type. type A = { id: number, title: string, type: stri ...