[Angular] Pipes as providers
2024-08-31 11:28:25
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>
最新文章
- Android之使用个推实现三方应用的推送功能
- Graphics平移缩放旋转(转载)+点睛
- 用scala实现一个sql执行引擎-(上)
- redmin3 忘记管理密码找回方法
- Net-Speeder为OpenVZ加速
- android利用数字证书对程序签名
- javaweb学习总结(四十七)——监听器(Listener)在开发中的应用
- Hadoop/Spark开发环境配置
- JAVA提高七:类加载器
- Python档案袋(文件系列操作 )
- C#Thread的方法、Start()、Sleep(int)、Abort()、Suspend()、Resume()
- 2018牛客网暑期ACM多校训练营(第九场)A -Circulant Matrix(FWT)
- Jmeter中通过beanshell写入CSV的脚本
- iOS 11开发教程(二十一)iOS11应用视图美化按钮之实现按钮的响应(1)
- Cracking The Coding Interview 3.6
- dict函数
- MTK 锁屏配置
- hdu1754 I Hate It(线段树单点更新,区间查询)
- 8-cin cout PK scanf printf(速度快慢问题对比)
- #npm install# MSBUILD : error MSB4132: 无法识别工具版本“2.0”。可用的工具版本为 ";4.0";。
热门文章
- 《开源公开课分享》:Java开源框架案例分享
- x264代码剖析(三):主函数main()、解析函数parse()与编码函数encode()
- SQL-android uri的使用(转载)
- bootstrap课程10 从外部引入视频到页面用什么标签
- 1.10 Python基础知识 - 序列:列表
- 15个常用的javaScript正则表达式--来自于javascript公众号
- app 自动化测试 Appium+python可以运行的代码
- C#中对XML的操作
- linux删除svn版本号库
- 从数据表中随机抽取n条数据有哪几种方法(join实现可以先查数据然后再拼接)