Zerok
Zerok

Reputation: 227

Pass HTML attribute value to function in angular 2

I have a custom element that I just want to show when I click a button. Then, when I click that button, I want to do something like...:

<my-element [hidden]="switchHidden()"></my-element>

... so if it's in false, it now will be true, and viceversa. A very typical approach.

But I don't know how I can pass to my function "switchHidden()" the value of the "hidden" attribute. How can I do this, so I can check whether it is true or false?

Thank you!

Upvotes: 1

Views: 1822

Answers (2)

Logan H
Logan H

Reputation: 3423

PLUNKER Demo

Just have a variable in your component that is a boolean for when you want to show and hide it.

let showElement: Boolean = true;

Then when you want to toggle it on/off with a button put this in the click.

<button (click)="showElement = !showElement">Toggle</button>

and that will flip the value of showElement every time the user clicks the button. So if showElement is true, when the user clicks the button it will make showElement false and thus hidding your element. Vise versa for when showElement is false, the user clicks the button making it true and thus showing your element.

Upvotes: 1

Vlado Tesanovic
Vlado Tesanovic

Reputation: 6424

Don't use hidden attribute, use:

<my-element *ngIf="switchHidden"></my-element>

http://angularjs.blogspot.ba/2016/04/5-rookie-mistakes-to-avoid-with-angular.html

Upvotes: 2

Related Questions