如何根据 Angular 的 *ngIf 的条件更改 css?

How to change css based on the conditions with Angular's *ngIf?

我正在使用 Angular 制作天气小部件。我想要白天和晚上不同的背景颜色。我正在使用 OpenWeather api 来获取数据。 OpenWeather 有一个方法 .isDay 如果是白天时间 returns 为真,晚上为假。我想用这个方法改变背景颜色

天气小工具-main.component.ts

  .....
  ...
  setWeatherData(data) {
    this.WeatherData = data;
    let sunsetTime = new Date(this.WeatherData.sys.sunset * 1000);
    this.WeatherData.sunset_time = sunsetTime.toLocaleTimeString();
    let currentDate = new Date();
    this.WeatherData.isDay = (currentDate.getTime() < sunsetTime.getTime());
    this.WeatherData.temp_celcius = (this.WeatherData.main.temp - 273.15).toFixed(0);
    this.WeatherData.temp_min = (this.WeatherData.main.temp_min - 273.15).toFixed(0);
    this.WeatherData.temp_max = (this.WeatherData.main.temp_max - 273.15).toFixed(0);
    this.WeatherData.temp_feels_like = (this.WeatherData.main.feels_like - 273.15).toFixed(0);
  }
  .....
  ...

天气小工具-main.component.html

<div id="divWeatherMain">
  <div *ngIf="WeatherData.isDay" class="weatherWidgetRow">
    <i class="fas fa-3x fa-sun sun"></i>
  </div>
  <div *ngIf="!WeatherData.isDay" class="weatherWidgetRow">
    <i class="fas fa-3x fa-moon moon"></i>
  </div>
  <div class="weatherWidgetRow cloudDiv">
    <i class="fas fa-3x fa-cloud cloud"></i>
  </div>

  <div class="weatherWidgetRow" style="font-size:32px; margin-top:5px;">
    {{WeatherData.temp_celcius}}°C
  </div>
  <div class="weatherWidgetRow" style="font-size:12px;">
    {{WeatherData.temp_min}}°C / {{WeatherData.temp_max}}°C
  </div>
  <div class="weatherWidgetRow" style="font-size:12px;">
    Feels Like: {{WeatherData.temp_feels_like}}°C
  </div>
  <div class="weatherWidgetRow" style="font-size:25px; margin-top:10px">
    {{WeatherData.name}}
  </div>
  <div class="weatherWidgetRow" style="font-size:12px;">
    Humidity: {{WeatherData.main.humidity}}%
  </div>
</div>

天气小工具-main.component.css

.....
...
#divWeatherMain {
  display: block;
  border-radius: 10px;
  width: 200px;
  height: 220px;
  background: rgb(0,0,0);
  background: linear-gradient(100deg, rgba(0,0,0,1) 0%, rgba(8,7,42,1) 100%);
  color: White;
  font-family: 'Segoe UI', Tamoha, Geneva, Verdana, sans-serif;
}
.....
...

您可以使用ngClass来实现这个

示例:

 <div class="weatherWidgetRow" [ngClass]="{'class1': WeatherData.isDay === ture, 'class2': WeatherData.isDay === false}">
    <i same for here you can use ng class to change the icon></i>
  </div>
<div class="weatherWidgetRow">
    <i [ngClass]="WeatherData.isDay ? fas fa-3x fa-sun sun : fas fa-3x fa-moon moon"></i>
</div>

你必须使用 ngClass,根据你的使用情况有不同的方法。

检查:

https://angular.io/api/common/NgClass

您可以使用

<div id="divWeatherMain">
<div class="weatherWidgetRow" [ngClass]=”WeatherData.isDay? day-bg-color: night-bg-color”> 
<i class="fas fa-3x" [ngClass]=”WeatherData.isDay?  fa-sun sun : fa-moon moon”></i> 
</div>
    
...
</div>