Jason Shultz Jason Shultz - 27 days ago 6
HTML Question

How can I show and hide dynamic divs triggered by dynamic buttons in Angular 2

I got this work using a click event and some plain javascript but I'm sure there is a better way for this.

I'm generating some dynamic rows and corresponding dynamic buttons using ngFor.

They look like this:

<div *ngFor="let section of data.order?.sections" id="{{section.class}}Detail" class="{{section.name | lowercase | removeAmpersand | removeSpaces }}">Random Text Here</div>

And then elsewhere on the page there is a list of anchor tags also generated using an ngFor:

<a (click)="showDetails($event)" id="{{section.name | lowercase | removeAmpersand | removeSpaces }}"><span class="icomoon icomoon-eye"></span> Detail/a>

My question is, what is the preferred way that I could show and hide the divs? Each of the divs starts off with a css property of
display: none
and I was hoping to just toggle that. Instead I'm just using the click event to run a function that gets the div id and then I have some pure javascript that looks like this:

myDiv.style.display = myDiv.style.display === '' ? 'block' : '';

What should I do that would be the preferred method?

Answer Source

You can conditionally add css classes to your elements. Something like

<div class="standardclass" [class.additionalclass]="showFlag"></div>

where additionalclass is another css class that will only be added if the expression showFlag is true. It can be any js expression, not just a flag.

You can also use *ngIf to conditionally add or remove the element from the dom entirely.

Search for "Angular 2 template syntax"