Angular (4 or 2) apply CSS if conditions are met
Asked Answered
O

4

5

I've found some code examples that explain how I can apply a class item if conditions are met.

In my .ts file I have the following:

private readNews : boolean = false;

[..]

  ngOnInit() {
    localStorage.setItem('readNews', 'Read');

    if (localStorage.getItem('readNews') != null || '') {
      this.readNews = true;
    }
  }

In my HTML I have the following inline CSS:

<i class="fal fa-cogs fa-5x"></i>

However, what I want it to be is the following:

If this.readNews === true

<i class="fal fa-cogs fa-5x blink"></i>

So it needs to add 'blink' in the CSS when the news is read (which is saved in localStorage).

Older answered 23/11, 2017 at 9:14 Comment(0)
D
6

try like this :

<i [ngClass]="readNews ? 'fal fa-cogs fa-5x blink': 'fal fa-cogs fa-5x'"></i>
Dough answered 23/11, 2017 at 9:24 Comment(1)
Thanks for the help of this suggestion! It made my code work. Got me on the right track. Did some changes overall too.Older
R
4

Use ngClass

<i [ngClass]="(readNews == 'Read')? 'fal fa-cogs fa-5x blink':'fal fa-cogs fa-5x'" ></i>

or you can call custom functions

[ngClass]="getClass()"

getClass(flag:string) {
  let cssClasses;
  if(localStorage.getItem('readNews') == 'Read') {  
     cssClasses = {
       'fal': true,
       'fa-cogs': true,
       'fa-5x': true,
       'blink': true
     }  
  } else {  
     cssClasses = {
       'fal': true,
       'fa-cogs': true,
       'fa-5x': true,
       'blink': false
     }  
  }
  return cssClasses;
}
Rovit answered 23/11, 2017 at 9:24 Comment(0)
I
0
<i [class.blink]="readNews"></i>

Based on cheat sheet on https://angular.io/guide/cheatsheet

Iconography answered 23/11, 2017 at 9:17 Comment(0)
C
-1

In HTML:

<i *ngIf="readNews" class="fal fa-cogs fa-5x"></i>
<i *ngIf="!readNews" class="fal fa-cogs fa-5x blink"></i>

And in typescript i would refactor as this to improve readability:

ngOnInit() {
localStorage.setItem('readNews', 'Read');
this.readNews = (localStorage.getItem('readNews') != null || '');

}

Chirrup answered 23/11, 2017 at 9:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.