*NgIf block in Angular does not toggle with two event functions

269 views Asked by At

I need to show and hidden(perfectly - totally clear to original state) block with images with two buttons.

For this I tried to make this job with NgIf block and boolean variable, but it works only with one button.How to separate toggling?

<button mat-raised-button color="warn" (click)="submit()">
          Find Cats!<img
            src="../../../assets/cat-sit.png"
            class="btn-image"
            alt="cat"
          />
        </button>
        <button mat-raised-button color="accent">
          Clear space...<img
            src="../../../assets/cat-run.png"
            class="btn-image"
            alt="cat"
            onclick="clear()"
          />
        </button>

// block, that I need(perfectly to render such one (empty) every time I use clear()).

<div *ngIf="show" id="img-container" class="images-container">
  <div *ngFor="let cat of cats" class="cat-container">
    <mat-card
      ><img mat-card-sm-image src="{{ cat.url }}" class="cat-image" alt="cat"
    /></mat-card>
  </div>
</div>

Funtions:

submit() {
    this.catsInfo.getCats(); // this part call service with restApi and data for cats
    if (!this.show) {
      this.show = !this.show;
    }
    
  }
clear() {
        if (this.show) {
        this.show = !this.show;
         }
   }
show: Boolean = false;
1

There are 1 answers

2
nevada_scout On

Your clear button is using onclick="clear()" so the Angular function will not be called. Change this to (click)="clear()" and it should work.

You can also simplify your clear() and submit() functions:

submit() {
    this.catsInfo.getCats(); // this part call service with restApi and data for cats
    this.show = true;
    
}
clear() {
    this.show = false;
}

show: Boolean = false;