Hi There I have been trying to filter an array with some success using ngIF and ngFor.
<button *ngFor="let item of items"> <div *ngIf="(item.data.type == 1)"> {{item.data.name}} </div> </button>
This code does only show buttons with name in it for data that has type=1 but it also create empty buttons for each data entry that doesn't have type=1, I can't figure out how to get rid of empty buttons. Any help is much appreciated.
Use ngFor and ngIf on same element It's very common scenario where we want to repeat a block of HTML using ngFor only when a particular condition is true. i.e., if ngIf is true.So in this case to use *ngIf and *ngFor on same element, place the *ngIf on a parent element that wraps the *ngFor element.
In Angular, we cannot use two structural directives on the same element. i.e., we cannot place *ngFor,*ngIf together on same element. The above code returns following error.
NgIf conditionally displays items by adding or removing them from the DOM depending on the condition. NgFor renders a list of items from iterable objects.
The *ngIf directive is most commonly used to conditionally show an inline template, as seen in the following example. The default else template is blank.
I would flip-flop your button
and div
:
<div *ngFor="let item of items"> <button *ngIf="(item.data.type == 1)">{{item.data.name}}</button> </div>
This way only buttons get created for valid items.
If <div>
's aren't desirable use <ng-container>
instead.
Though not advisable due to performance reasons, you can also use a function in your component:
<button *ngFor="let item of filterItemsOfType('1')">{{item.data.name}}</button>
Where your component has a function:
filterItemsOfType(type){ return this.items.filter(x => x.data.type == type); }
While this works, it is not recommended and should be avoided where possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With