0

I want to display this span

<span class="badge badge-danger">RARE</span>

only if this condition is true


listComics() {
    this.comicsService.getComics().subscribe(
      comicsList => {
        this.comics = comicsList.data.results;
        this.rareComic = comicsList.data.results[Math.floor(Math.random() * this.comics.length)];

        for(var i = 0; i < this.comics.length; i++){
           if(this.comics[i] == this.rareComic){
           console.log(this.comics[i])
           console.log(this.rareComic)
           //Both are the same


          }
        }
   });
  }

I tried using *ngIf and [hidden] but no success.

nircraft
  • 8,242
  • 5
  • 30
  • 46
  • what is your controlling data/object for hiding or saving? which variable do you want to use? – nircraft Apr 19 '19 at 13:19
  • 2
    `*ngIf="rareComic == comic"` – Explosion Pills Apr 19 '19 at 13:19
  • Thank you, Explosion Pills! It works! But do you now how can I get 2 or more rareComic? For example: I have 24 comics and I want to display 4 comics with this rare span, do you have any ideia? – Caio Henrique Apr 19 '19 at 13:23
  • Heretic Monkey, I saw it, but I didn't know I could compare inside the *ngIf or [hidden]. – Caio Henrique Apr 19 '19 at 13:26
  • @CaioHenrique how would you do it in put TypeScript? I see two solutions: set a boolean attribute 'rare' on the comics that are rare, and check that boolean attribute; or add all rare comics to a set of rare comics, and check if the comic is contained in that set. If you can write the condition in TypeScript, then good news: it's the same condition in the angular template. – JB Nizet Apr 19 '19 at 13:27

1 Answers1

3

There are 2 approaches by which you can show or hide an element in angular

  1. By using ngIf structural directive. It is advised only when your bound condition wont change often. As I understand, your condition could be

    *ngIf="rareComic == comic"
    
  2. Class binding. Use this to add or remove a class to an element as

    [class.active]="rareComic == comic"
    

And active class will have styles to show the item. Use this when a user will interact on the page and is expected that the element's visibility will toggle

Saksham
  • 9,037
  • 7
  • 45
  • 73