Angular2中如何用*ngIf动态设置类名?天气仪表盘开发问题
Hey there! Let's work through this problem with your weather dashboard—since you're dealing with an Observable of weather data, we just need to adjust how we process the data before using it in your template. Here are two clean approaches to add those custom class properties:
Option 1: Process data when subscribing to the Observable
You can transform the array directly inside the subscribe block by mapping each weather item to a new object with your custom property:
// Assume your service returns an Observable<WeatherItem[]> this.weatherService.getWeatherData().subscribe(weatherItems => { // Create a new array with modified items this.processedWeather = weatherItems.map(item => { return { ...item, // Keep all original properties weatherClass: item.temperature > 70 ? 'weatherdata-sun-hot' : 'weatherdata-sun-normal' }; }); });
Then in your HTML, loop through the processed array and use the new property with ngClass (this is cleaner than repeating *ngIf blocks):
<div *ngFor="let day of processedWeather"> <div [ngClass]="day.weatherClass"> <p>Temperature: {{ day.temperature }}°F</p> <!-- Other weather details --> </div> </div>
Option 2: Use RxJS map operator (Recommended for reactive flow)
For a more Angular-friendly approach, handle the data transformation directly in the Observable pipeline using the map operator. This keeps your data stream reactive and avoids manual subscription cleanup:
import { map } from 'rxjs/operators'; // In your component this.processedWeather$ = this.weatherService.getWeatherData().pipe( map(weatherItems => { return weatherItems.map(item => ({ ...item, weatherClass: item.temperature > 70 ? 'weatherdata-sun-hot' : 'weatherdata-sun-normal' })); }) );
Then use the async pipe in your template to automatically manage the subscription:
<div *ngFor="let day of processedWeather$ | async"> <div [ngClass]="day.weatherClass"> <p>Temperature: {{ day.temperature }}°F</p> </div> </div>
Quick note if you really want to use *ngIf
If you prefer not to add a custom property and want to check the temperature directly in the template, you can do this (though it repeats code a bit):
<div *ngFor="let day of processedWeather$ | async"> <div *ngIf="day.temperature > 70" class="weatherdata-sun-hot"> <p>Temperature: {{ day.temperature }}°F</p> </div> <div *ngIf="day.temperature <= 70" class="weatherdata-sun-normal"> <p>Temperature: {{ day.temperature }}°F</p> </div> </div>
The key idea here is that we're creating new objects (using the spread operator ...item) instead of trying to modify the original data directly—this works because API responses are often immutable, and it keeps your data flow predictable.
内容的提问来源于stack exchange,提问作者user3332010

