Roka545 Roka545 - 1 year ago 81
AngularJS Question

Conditional to toggle button display based on number of items

I have an ngFor that display's buttons based on a list of items in HTML. The list can contain 0 or more items. I would like to toggle display of an additional button based on the number of items in that list e.g. if there are 0 items in the list then the button will not display; if there are more than 0 items in the list then the button will display. Here's my code:

<div class="panel-body">
<!--Panel Body-->
<button *ngFor="#trainingItem of trainingItems" type="button" style="text-align:left; margin-right: 10px;" class="btn btn-secondary btn-block">
<strong>Name: </strong> {{trainingItem.Name}}
<strong>Location: </strong> {{trainingItem.LocationName}}

<!--This is the button I want to toggle based on the number of items-->
<button type="button" class="btn btn-primary btn-block" style="background-color: #323232; margin-top: 10px">Start Training</button>

I know I can handle this by creating a function in my Typescript class that toggles a value based on the number of items in the list, but I would like to handle this entirely on the HTML side and prevent the need to create an entire function in another file.

Answer Source

You should be able to check the arrays length in a ngIf:

<button *ngIf="trainingItems.length" ...>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download