How do I filter elements when using ng-for?
<tr>
<td *ng-for="#col of columns" ><a (click)="sort(col.name)">{{col.title}}</a></td>
</tr>
I don't want to create a element when col.visible is false
How do I do this in Angular2?
How do I filter elements when using ng-for?
<tr>
<td *ng-for="#col of columns" ><a (click)="sort(col.name)">{{col.title}}</a></td>
</tr>
I don't want to create a element when col.visible is false
How do I do this in Angular2?
You can use a pipe to filter the data so that only a subset is used by *ngFor
like explained in
How to apply filters to *ngFor
or you can use *ngIf
with *ngFor
, but they are not allowed on the same element. How to use them together anyway is explained in *ngIf and *ngFor on same element causing error
Use ngIf directive. col.visible = true means only the td is added otherwise it won't be added in the tr.
The ngIf directive removes or recreates a portion of the DOM tree based on an {expression}. If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.
<tr>
<td ng-if="col.visible" ng-for="#col of columns" ><a ng-click="sort(col.name)">{{col.title}}</a></td>
</tr>
In this case the simplest thing to do is to ensure that your columns array is only populated with col objects where col.visible === true
.
Doing that in the controller class will fix this problem without any markup filters or other framework specific dependencies.
Angular2 syntax has changed a bit. For the release, the syntax for a *ngIf is:
<div class="row pre-scrollable" *ngIf="count > 0">
<div *ngFor="let image of results">
{{image.title}}
</div>
</div>
The results is an array of some objects that have a title and count is the number of items in that array.
In this case, the div is used to have a scrollable list of results and if there are no results, to hide the scrollbar.