0

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.

3
  • 4
    you need conditional class, see this stackoverflow.com/questions/35269179/… Commented Apr 20, 2018 at 20:57
  • @AliAdravi: Thanks for the hint but I cannot see the if/else mechanism there. Like if val greater than something than use classname x otherwhise classname y. Can you give me a quick example? :-) Thanks again. Commented Apr 20, 2018 at 21:05
  • @AliAdravi: I've come up with a working solution I tried: <li *ngFor="let item of weatherdata" [ngClass]="[item.main.temp_max > 17 ? 'weather-sun-hot' : 'weather-sun-normal']" >{{item.dt_txt}} | {{item.main.temp_min}} -> {{item.main.temp_max}}</li> But for me it's looking like ugly code. Or would you implement it the same way? I am confused. Commented Apr 20, 2018 at 21:09

1 Answer 1

1

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
        };
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the perspective... I should have thought of that :-) So easy and good. Have a nice day.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.