You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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>

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:33:39