pPeter
pPeter

Reputation: 81

Angular 2 - Click to show and hide

I want to use a button to show and hide elements in my HTML. I know i have to use a boolean in the typescript and *ngIf in the HTML.

In my typescript i have a boolean:

showHide: false;

In my HTML i have:

<button (click) = "showHide=true" </button>

I use this to hide elements. I hide my elements with the use of *ngIf="showHide" on the elements i want to hide.

But how can i bring back the elements i have hidden with the same button?

Upvotes: 2

Views: 41253

Answers (2)

coreuter
coreuter

Reputation: 3572

You could use a function to change from true to false and vice versa instead of just setting showHide true each time you click the button.

To do so you need to create a function e.g. changeShowStatus to change the value of showHide.

changeShowStatus(){
    this.showHide = !this.showHide;
  }

Then you call this function every time you hit the button by changing your showHide=true to changeShowStatus():

<button type="button" (click)="changeShowStatus()">show/hide</button>

To set the initial status you could set the showHide value in the constructor and define showHide just as boolean:

export class App {
  ...
  showHide: boolean;

  constructor() {
    this.showHide = true;
  }
  ...
}

Plunker: show/hide div with TS/Angular2

Upvotes: 10

Tiep Phan
Tiep Phan

Reputation: 12596

try this

<button (click)="showHide = !showHide">click</button>

Upvotes: 13

Related Questions