前端修仙之路

Angular自定义pipe实现

2019-01-26  本文已影响105人  欧博觅斯

angular尽管内置许多的pipe,比如date、async、currency等。尽管拿来即用,但是远不能满足于业务的一些需求,所以需要实现自定义的一些pipe。

自定义pipe(AngularJS中的filter概念)就是允许让我们去创建一个纯函数接收一些参数实际上去做一些形式上的转换。下面让我们做一些进一步的了解。

让我们假设下,如果我们通过拖拽文件上传接收到的一个图片文件,那么我们很可能会收到如下的信息:

export class FileComponent {
    file = { name: 'logo.svg', size: 2120109, type: 'image/svg' }
}

在这里,我们可能更加关注的是size这个属性,也是我们接下来要使用pipe的属性。我们在实现这个fiesize pipe后,会自动转换为MB,使用的代码是这样的。

<div>
    <p>{{file.name}}</p>
    <p>{{file.size | filesize }}</p>
</div>

在创建自定义pipe之前,我们需要创建一个类,语义化角度上来考虑,就命名为FileSizePipe。

export class FileSizePipe {
}

鉴于上面的html中使用,我们需要给我们pipe命名为filesize,当然这些都是在ts的decorator @pipe中完成的。

import { Pipe } from '@angular/core'
@Pipe({
    name: 'filesize'
})
export class FileSizePipe {}

我们要做的就是提供一个name属性,@Pipe会自动帮我们完成。
当然还有一步最重要的要做的就是在ngModule中声明我们刚刚创建的pipe。

// ...
import { FileSizePipe } from './FileSizePipe'

@NgModule({
    declartions: [
        // ....
        FileSizePipe
    ]
})
export class AppModule {}

自定义pipe一般会是一个很常用的工具类,如果你想在所有的模块中共享这个pipe,简单在NgModule的exports字段声明即可。

在我们创建自定义pipe的时候,最重要的一步就是需要实现PipeTransform接口(typescript中引入的概念),接下来我们实现代码:

import { Pipe, PipeTransform } from '@angular/core'

@Pipe({ name: 'filesize' })
export class FileSizePipe implements PipeTransform {
    transform (size: number) {
        return (size / (1024 * 1024)).toFixed(2) + 'MB'
    }
}

这时候再去看我们的template,在浏览器中的显示情况可能会不一样了。

<!-- 2.02MB -->
{{ file.size | filesize }}
import { Pipe, PipeTransform } from '@angular/core'

@Pipe({ name: 'filesize' })
export class FileSizePipe implements PipeTransform {
    transform (size: number, extension: string = 'MB') {
        return (size / (1024 * 1024)).toFixed(2) + extension
    }
}

那在使用的时候,我们如果需要中文显示兆,可以在我们template这样使用:

<div>
    <p>{{file.name}}</p>
    <p>{{file.size | filesize: "兆" }}</p>
</div>

做了这么多,那如果我们需要使用GB单位,那要怎样实现呢?赶快动起手来自己实现一下吧。
原文查看

上一篇下一篇

猜你喜欢

热点阅读