Search code examples
angularclassnameangular-ng-if

Angular2 use *ngif to set class name in html code


I've tried some stuff cause I am building a weather dashboard.

I load weather data with http and subscribe, so I'll getting an observable back I cannot go trough like an array in typescript to add new properties.

For example I want to look on each weather data and look if a value has more than 70 °F and tell the weatherdata item to add a new property "weatherdata-sun-hot". Otherwise it should use an other class name "weatherdata-sun-normal" I would use this as a class name to put it in html later with interpolation.

So my idea is to solve this with the html template

So far I do have my code here

<ul>
   <li *ngFor="let item of weatherdata">{{item.dt_txt}} | {{item.main.temp_min}} -> {{item.main.temp_max}}</li>
</ul>

Is there an elegant way to solve this?

Thanks for any help.


Solution

  • You need to use ngClass directive:

    <ul>
        <li *ngFor="let item of weatherdata" [ngClass]="{'weatherdata-sun-hot': item.main.temp_min > 70, 'weatherdata-sun-normal': item.main.temp_min <= 70}">
            {{item.dt_txt}} | {{item.main.temp_min}} -> {{item.main.temp_max}}
        </li>
    </ul>
    

    Or you can do it in the component's code and bind to it:

    template

    <ul>
        <li *ngFor="let item of weatherdata" [ngClass]="tempClass(item)">
            {{item.dt_txt}} | {{item.main.temp_min}} -> {{item.main.temp_max}}
        </li>
    </ul>
    

    component

    @Component(...)
    class MyComponent {
        tempClass(item): any {
            const hot = item.main.temp_min > 70;
            return {
                'weatherdata-sun-hot': hot,
                'weatherdata-sun-normal': !hot
            };
        }
    }