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

14

I'm making a weather widget with Angular. I want different background colors for the day and the night. I'm using OpenWeather apis for fetching the data. OpenWeather has a method .isDay that returns true if it's day time and false for the night. I want to use this method to change the background color.

weather-widget-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);
  }
  .....
  ...

weather-widget-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" >
    {{WeatherData.temp_celcius}}°C
  </div>
  <div class="weatherWidgetRow" >
    {{WeatherData.temp_min}}°C / {{WeatherData.temp_max}}°C
  </div>
  <div class="weatherWidgetRow" >
    Feels Like: {{WeatherData.temp_feels_like}}°C
  </div>
  <div class="weatherWidgetRow" >
    {{WeatherData.name}}
  </div>
  <div class="weatherWidgetRow" >
    Humidity: {{WeatherData.main.humidity}}%
  </div>
</div>

weather-widget-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;
}
.....
...

answered question

1 Answer

4

You can use ngClass to achieve this

Example:

 <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>

posted this

Have an answer?

JD

Please login first before posting an answer.