Hide / show with *ngIf Angular2

Alexandr Belov picture Alexandr Belov · Jan 20, 2017 · Viewed 13k times · Source

I have two elements which I want to hide and show based on *ngIf condition value.

By default my wrap block is visible and when I click on one of its divs this wrapblock should disappear and only the chosen div's content should be displayed inside my span element. Then when I click on my span element it should disappear and wrap block should come again with all its default content.

To implement that I use *ngIf with value visability for both elements, expecting that my functions work in following way:

wrap - visible;
span - hidden;

wrap - hidden;
span - visible;

Here's my code:

@Component({
selector: 'my-app',
template: `
<div id="wrap" class="wrap" *ngIf="visability">
<div (click)="clicked($event)">
  <h2>Hello {{name}}</h2>
</div>
<div (click)="clicked($event)">
  <h2>Hello {{year}}</h2>
</div>
<div (click)="clicked($event)">
  <h2>Hello {{surname}}</h2>
</div>
<div (click)="clicked($event)">
  <h2>Hello {{country}}</h2>
</div>
<div (click)="clicked($event)">
  <h2>Hello {{cartoon}}</h2>
</div>

 <div class="view">
  <span id="span" (click)="showDivs()" *ngIf="visability">{{target}}    </span>
 </div>

 `,
})
export class App {
name:string;
year: string;
surname: string;
country: string;
cartoon: string;
element: any;
target: any;

constructor() {
var wrap = document.getElementById("wrap");
var span = document.getElementById("span");
this.name = 'Angular2'
 this.year = '1989'
  this.surname = 'Connor'
   this.country = 'USA'
    this.cartoon = 'Tom & Jerry'
  }

clicked(event) {
wrap.visability = false;
span.visability = true;
this.target = event.target.innerText;
} 

showDivs(){
span.visability = false;
wrap.visability = true;
}

}

My Plunker

Why my functions don't work in a proper way?

Answer

AJT82 picture AJT82 · Jan 20, 2017

I actually changed your code a bit. Put visability as true for the first div, and false for the second. To separate them better. Then it's just to toggle the booleans based on click, like so:

First declare the visability as a variable so that you can refer to it with this then just toggle the visability.

  clicked(event) {
    this.visability = false;
    this.target = event.target.innerText;
  }

and

  showDivs(){
    this.visability = true;
    // span.visability = false; // remove this
    // wrap.visability = true;  // remove this
  }

and the html accordingly:

<div id="wrap" class="wrap" *ngIf="visability">

and

<span id="span" (click)="showDivs()" *ngIf="!visability">{{target}}</span>

This is one solution.

Your plunker