我尝试在我的表格中显示最大值和最小值我们如何使用角度2内置管道在这里尝试这样
<td > {{value.max | MaxMinPipe}} </td>
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'MaxMinPipe'
})
export class MaxMinPipe implements PipeTransform {
transform(value) {
return Math.max(value);
}
}
答案 0 :(得分:2)
<td > {{rpi.north_h | max}} </td>
<td > {{rpi.north_h | min}} </td>
答案 1 :(得分:1)
好吧,我可以看到两种方法来实现这个目标:
1st。 - 创建一个返回(最大值和最小值)的管道 - IMO,这是更好的方法:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'maxMin'
})
export class MaxMinPipe implements PipeTransform {
transform(value: any[], prop: string) {
if (!Array.isArray(value) || value.length === 0 || !prop) {
return value;
}
// Here we sort the items based on passed `property`
value.sort((a, b) => b[prop] - a[prop]);
const max = value[0][prop];
const min = value[value.length - 1][prop];
return [max, min];
}
}
而不是sort
你也可以使用这样的东西(不确定哪一个有更好的性能):
const mappedArr = value.map(x => x[prop]);
const max = Math.max(...mappedArr);
const min = Math.min(...mappedArr);
<强>模板强>:
<table>
<tr>
<th>Max value</th>
<th>Min value</th>
</tr>
<tr *ngIf="data | maxMin: 'myProperty' as result">
<td>{{ result[0] }}</td>
<td>{{ result[1] }}</td>
</tr>
</table>
请注意,使用上面的as
语法,除了提高性能之外,因为它只调用管道一个时间,它提供了更多的可读性:)
第二。 - 分成2个管道,如下所示:
<强> MaxPipe 强>:
...
export class MaxPipe implements PipeTransform {
transform(value: any[], prop: string) {
if (!Array.isArray(value) || value.length === 0 || !prop) {
return value;
}
value.sort((a, b) => b[prop] - a[prop]);
return value[0][prop];
}
}
<强> MinPipe 强>:
...
export class MinPipe implements PipeTransform {
transform(value: any[], prop: string) {
if (!Array.isArray(value) || value.length === 0 || !prop) {
return value;
}
value.sort((a, b) => a[prop] - b[prop]);
return value[0][prop];
}
}
在模板:
中<td>{{ data | max: 'yourProperty' }}</td>
<td>{{ data | min: 'yourProperty' }}</td>
请注意,您必须传递要用于比较的属性,然后获取最小值和最大值。可能在你的情况下它是“north_h”。
<强>提示:强>
Pipe
添加到NgModule
的声明中。答案 2 :(得分:0)
import { PipeTransform, Pipe} from '@angular/core';
@Pipe({
name: 'MaxValueFilter'
})
export class MaxPipe implements PipeTransform {
transform(value:any[]) : number {
let maxValue : number = value[0].north_h;
for(var val in value){
if(maxValue < val.north_h){
maxValue = val.north_h;
}
}
return maxValue;
}
}