Folky.H
Folky.H

Reputation: 1204

Angular2 - *ngIf : How to show a specific element?

I am willing to show only a specific element using ngIf; however, for some reason, it does not work.

The issue: When I click to show only a specific element, all the other elements shows up!

The code:

HTML (elements is taken from an async request)

<ion-col *ngFor="#finalFormat of elements">
<div *ngIf="currentElement">
<div>Show this element</div>
</div>
<div (click)="showThis(finalFormat.elementName)" *ngIf="!currentElement">CLICK TO SHOW</div></ion-col>

JS:

    showThis(element){
    if(this.currentElement === element){
      return;
    }
    this.currentElement = element;
    }

Upvotes: 1

Views: 503

Answers (2)

dfsq
dfsq

Reputation: 193251

I think it can be simpler:

<ion-col *ngFor="#finalFormat of elements">
  <div *ngIf="finalFormat.currentElement">
    <div>Show this element</div>
  </div>
  <div (click)="showThis(finalFormat)" *ngIf="!finalElement.currentElement">CLICK TO SHOW</div>
</ion-col>

and in controller:

showThis(element) {
  element.currentElement = !element.currentElement;
}

So you basically just modify currentElement property of individual finalFormat objects.

Upvotes: 0

Thierry Templier
Thierry Templier

Reputation: 202138

I would update the test like this:

<div *ngIf="currentElement === finalFormat.elementName">
  (...)
</div>

Same for the "CLICK TO SHOW" block:

<div (click)="showThis(finalFormat.elementName)" 
     *ngIf="!currentElement !== finalFormat.elementName">
  CLICK TO SHOW
</div>

Upvotes: 1

Related Questions