I'm building a mean stack project and I was trying to show elements in a table only if their number in a predefined range of numbers. I found a way to resolve the problem by using this :
<ng-container *ngFor="let item of mf.data">
<tr *ngIf="(item.num > 4) && (item.num < 10)">
but I'm still wondering if there is a better way to do it something like this (which didn't work):
*ngIf="item.num === [5,9]"
is there any other solution?
CodePudding user response:
You could use a pipe maybe, then your ngIf could be something like:
*ngIf="item.num | between:5:9"
@Pipe({name: 'between'})
export class BetweenPipeimplements PipeTransform {
transform(value: number, start: number, end: number): boolean{
return value > start && value < end;
}
}
CodePudding user response:
Prepare your data using the regular array methods and save it to the property:
export class TestComponent implements OnInit {
public items!: { num: number }[];
public ngOnInit(): void {
// some test objects...
const testData = [...Array(20).keys()].map(item => {
return { num: item };
});
this.items = testData.filter(item => item.num > 4 && item.num < 10);
}
}
And just get the items you need:
<table>
<tr *ngFor="let item of items">
<td>item #{{ item.num }}</td>
</tr>
</table>
You can use other events (such as a button click) to update this collection.
Note: don't use functions in *ngFor data source (like *ngFor="let item of loadItemsFromServer()).
The change detection process will call it many times.
