I made my custom pipe to get the lowest number in an array and came up with this simple code but it does not work. It displays blank when rendered.
@Pipe({
name: 'min'
})
export class MinPipe implements PipeTransform {
transform(items: any ): any {
return Math.min.apply( Math, items );
}
}
I use it like this:
<div *ngFor="let vars of variations">
<div class="price-start">Starts at: {{vars.variationCost | min}}</div>
</div>
Any help would be appreciated :)
I am not sure why you chose to delete the previous question that explained the issue better. At the moment the question is running into the XY problem.
Nevertheless, I presume from the previous question that you wish to filter the array based on the value held by the variationCost
property. For that you could do a simple *ngIf
inside the *ngFor
as I suggested in the other question. If you want to use a pipe, it'd need to be applied to the *ngFor
directive.
Try the following
less-than.pipe.ts
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({ name: "lessThan", pure: true })
export class LessThanPipe implements PipeTransform {
transform(collection: Array<any>, key: string, boundary: number): Array<any> {
if (!collection) {
return null;
}
return collection.filter(item => item[key] < boundary);
}
}
Component
import { Component } from "@angular/core";
@Component({
selector: "my-app",
template: `
<div *ngFor="let vars of (variations | lessThan: 'variationCost':45)">
<div class="price-start">Starts at: {{ vars.variationCost }}</div>
</div>
`,
styleUrls: ["./app.component.css"]
})
export class AppComponent {
variations = [
{ variationCost: 40 },
{ variationCost: 50 },
{ variationCost: 70 },
{ variationCost: 30 },
{ variationCost: 10 }
];
}
To display only the minimum of the array, you don't really need the *ngFor
directive. You could whip up a quick pipe and use it in conjunction with *ngIf
directive.
Try the following
min.pipe.ts
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({ name: "min", pure: true })
export class MinPipe implements PipeTransform {
transform(collection: Array<any>, key: string): Array<any> {
if (!collection) {
return null;
}
// credit: https://stackoverflow.com/a/31844649/6513921
return collection.reduce((acc, curr) =>
acc[key] < curr[key] ? acc : curr
);
}
}
Template
<div *ngIf="(variations | min: 'variationCost') as minVar">
<div class="price-start">Starts at: {{ minVar.variationCost }}</div>
</div>
Working example: Stackblitz