Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply a condition using ngFor and ngIf in angular 2 [duplicate]

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.

like image 252
DN0300 Avatar asked Mar 21 '17 15:03

DN0300


People also ask

Can we use both ngIf and ngFor together?

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.

Why ngFor and ngIf Cannot be used together?

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.

What is the difference between ngFor and ngIf?

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.

What is the use of * in ngIf?

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.


1 Answers

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.

like image 113
Tyler Jennings Avatar answered Sep 29 '22 23:09

Tyler Jennings