I have the following code:
This is the HTML view:
<button type="button" (click)="filterIt('male')">Filter male gender</button>
<table>
<ng-container *ngFor="let item of array;let i=index">
<tr class="border-bottom" *ngIf="item.condition==condition_var">
<td>{{i+1}}</td>
<td>{{item.condition}}</td>
</tr>
</ng-container>
</table>
This is the typescript file (.ts):
condition_var:string;
filterIt(value){
this.condition_var=value;
}
NOTE: the array variable is already populated. (array of objects:
[{}]
)
My question is: Is it a practice in angular2 to always declare variables and to work with them in expressions, ngIf, ngFor etc. Or can I use a better way rather than populating my class with too many variables which doesn't look good.
To be more specific, is there a better way to write this code?
Yes there is a better (more idiomatic) way to do this: use a
@Pipe
.Implement with:
And set the
condition
however you like. Note that filters can accept more than one positional parameter, separated by colons.Remember to add the pipe to whichever
@NgModule
s you use the pipe in:And if the
@NgModule
in question is a lazy-loaded "shared" module, don't forget to re-export it:This answer is currently valid as of angular
4.3.6
.