您好,欢迎访问一九零五行业门户网

深入了解Angular中的PIPE(管道)

在angular中,pipe(管道)可以用来对输入的数据进行处理,且不同的管道具有不同的作用。那么具体要怎么使用pipe(管道)?下面本篇文章就来带大家深入研究一下angular中的pipe(管道),看看它的使用方法。
pipe,翻译为管道。angular 管道是编写可以在html组件中声明的显示值转换的方法。angular 管道之前在 angularjs 中被称为过滤器,从 angular 2开始就被称为管道。管道将数据作为输入并将其转换为所需的输出。
angular pipes 将整数、字符串、数组和日期作为输入,用| 分隔,然后根据需要转换成格式,并在浏览器中显示出来。在插值表达式中,可以定义管道并根据情况使用它,在 angular 应用程序中可以使用许多类型的管道。
【相关教程推荐:《angular教程》】
内建管道string -> string
uppercasepipe
lowercasepipe
titlecasepipe
number -> string
decimalpipe
percentpipe
currencypipe
object -> string
jsonpipe
datepipe
tools
slicepipe
asyncpipe
i18npluralpipe
i18nselectpipe
使用方法大写转换<div> <p ngnonbindable>{{ 'angular' | uppercase }}</p> <p>{{ 'angular' | uppercase }}</p> <!-- output: angular --></div>
日期格式化<div> <p ngnonbindable>{{ today | date: 'shorttime' }}</p> <p>{{ today | date: 'shorttime' }}</p> <!-- output: 以当前时间为准,输出格式:10:40 am --></div>
数值格式化<div> <p ngnonbindable>{{ 3.14159265 | number: '1.4-4' }}</p> <p>{{ 3.14159265 | number: '1.4-4' }}</p> <!-- output: 3.1416 --></div>
javascript 对象序列化<div> <p ngnonbindable>{{ { name: 'semlinker' } | json }}</p> <p>{{ { name: 'semlinker' } | json }}</p> <!-- output: { "name": "semlinker" } --></div>
管道参数管道可以接收任意数量的参数,使用方式是在管道名称后面添加:和参数值。如number: '1.4-4',若需要传递多个参数则参数之间用冒号隔开,具体示例如下:
<div> <p ngnonbindable>{{ 'semlinker' | slice:0:3 }}</p> <p>{{ 'semlinker' | slice:0:3 }}</p> <!-- output: sem --></div>
管道链可以将多个管道连接在一起,组成管道链对数据进行处理。
<div> <p ngnonbindable>{{ 'semlinker' | slice:0:3 | uppercase }}</p> <p>{{ 'semlinker' | slice:0:3 | uppercase }}</p></div>
自定义管道下面以过往项目中使用的管道为示例,讲解自定义管道步骤:
使用 @pipe 装饰器定义 pipe 的 metadata 信息,如 pipe 的名称 - 即 name 属性
实现 pipetransform 接口中定义的 transform 方法
定义import { pipe, pipetransform } from "@angular/core";@pipe({ name: "formaterror" })export class formaterrorpipe implements pipetransform { constructor() {} transform(value: any, module: string) { if (value.code) { return value.desc; } else { return value.message; } }}
使用<div *ngif="errormessage"> <div class="message-box error mb-16" [@animate]="{value:'*',params:{opacity:'0',duration:'200ms'}}"> {{errormessage.error | formaterror:"auth"}} </div></div>
完~
更多编程相关知识,请访问:编程教学!!
以上就是深入了解angular中的pipe(管道)的详细内容。
其它类似信息

推荐信息