In this example, we are going to see how to use Pipe as providers inject into component.

We have the pipe:

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

@Pipe({
name: 'filesize'
})
export class FileSizePipe implements PipeTransform{
transform(value: number, ext: string = "MB") {
return (value / ( * )).toFixed() + ' ' + ext;
}
}

We want to inject this pipe as provider to the component:

import { Component, OnInit } from '@angular/core';
import {FileSizePipe} from './filesize.pipe'; interface File {
name: string,
size: number | string,
type: string
} @Component({
selector: 'app-root',
template: `
<div>
<div *ngFor="let file of files">
<p>{{ file.name }}</p>
<p>{{ file.size | filesize: 'MB' }}</p>
</div>
<hr>
<div *ngFor="let file of mapped">
<p>{{ file.name }}</p>
<p>{{ file.size }}</p>
</div>
</div>
`,
providers: [
FileSizePipe
]
})
export class AppComponent implements OnInit {
files: File[];
mapped: File[]; constructor(
private fp: FileSizePipe
) {
} ngOnInit() {
this.files = [
{ name: 'logo.svg', size: , type: 'image/svg' },
{ name: 'banner.jpg', size: , type: 'image/jpg' },
{ name: 'background.png', size: , type: 'image/png' }
];
this.mapped = this.files.map((file) => ({
name: file.name,
type: file.type,
size: this.fp.transform(Number(file.size), 'mb')
}));
}
}

As we can see, we use 'providers' keyword in the @Component:

  providers: [
FileSizePipe
]

This enable us to inject pipe into component:

  constructor(
private fp: FileSizePipe
) {
}

Then we just need to call transform method on the pipe:

    this.mapped = this.files.map((file) => ({
name: file.name,
type: file.type,
size: this.fp.transform(Number(file.size), 'mb')
}));

In the html. we don't need to use '|filesize: 'MB'' anymore:

      <div *ngFor="let file of mapped">
<p>{{ file.name }}</p>
<p>{{ file.size }}</p>
</div>

最新文章

  1. Android之使用个推实现三方应用的推送功能
  2. Graphics平移缩放旋转(转载)+点睛
  3. 用scala实现一个sql执行引擎-(上)
  4. redmin3 忘记管理密码找回方法
  5. Net-Speeder为OpenVZ加速
  6. android利用数字证书对程序签名
  7. javaweb学习总结(四十七)——监听器(Listener)在开发中的应用
  8. Hadoop/Spark开发环境配置
  9. JAVA提高七:类加载器
  10. Python档案袋(文件系列操作 )
  11. C#Thread的方法、Start()、Sleep(int)、Abort()、Suspend()、Resume()
  12. 2018牛客网暑期ACM多校训练营(第九场)A -Circulant Matrix(FWT)
  13. Jmeter中通过beanshell写入CSV的脚本
  14. iOS 11开发教程(二十一)iOS11应用视图美化按钮之实现按钮的响应(1)
  15. Cracking The Coding Interview 3.6
  16. dict函数
  17. MTK 锁屏配置
  18. hdu1754 I Hate It(线段树单点更新,区间查询)
  19. 8-cin cout PK scanf printf(速度快慢问题对比)
  20. #npm install# MSBUILD : error MSB4132: 无法识别工具版本“2.0”。可用的工具版本为 &quot;4.0&quot;。

热门文章

  1. 《开源公开课分享》:Java开源框架案例分享
  2. x264代码剖析(三):主函数main()、解析函数parse()与编码函数encode()
  3. SQL-android uri的使用(转载)
  4. bootstrap课程10 从外部引入视频到页面用什么标签
  5. 1.10 Python基础知识 - 序列:列表
  6. 15个常用的javaScript正则表达式--来自于javascript公众号
  7. app 自动化测试 Appium+python可以运行的代码
  8. C#中对XML的操作
  9. linux删除svn版本号库
  10. 从数据表中随机抽取n条数据有哪几种方法(join实现可以先查数据然后再拼接)