Angular Pipe管道理解及用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xnh_565175944/article/details/82115710

1.什么是Pipe?

       就是管道,简单来说,管道的作用就是传输。并且不同的管道具有不同的作用。(其实就是处理数据)

2.pipe用法

       {{ 输入数据 | 管道 : 管道参数}}  (其中‘|’是管道操作符)

3.Angular自带的pipe函数

管道

功能

DatePipe

日期管道,格式化日期

JsonPipe

将输入数据对象经过JSON.stringify()方法转换后输出对象的字符串

UpperCasePipe

将文本所有小写字母转换成大写字母

LowerCasePipe

将文本所有大写字母转换成小写字母

DecimalPipe

将数值按照特定的格式显示文本

CurrentcyPipe

将数值进行货币格式化处理

SlicePipe

将数组或者字符串裁剪成新子集

PercentPipe

将数值转百分比格式

 

例如: person.name | uppercase

       左边和右边都有对应的数据。person.name是一个容器,容器装了一个name,当name碰到管道之后会把name给uppercase,uppercase的作用就是把name转换。左边输出 右边接收,右边再输出。

      

4.简单使用pipe自带函数

       html(不使用管道的情况)

<p>My birthday is </p>{{birthday}}

       typescript

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  birthday = new Date(2018, 6, 13);
}
运行结果:

这样的结果用户看到了估计直接头大了是吧。

 

html(使用pipe后)

<p>My birthday is </p>{{birthday|date}}

结果

5.自定义管道:

首先打开Node.js cd到项目文件夹下

输入指令  ng g pipe pipe-name

成功后会出现两个文件:

       pipe-name.pipe.spec.ts   //测试

       pipe-name.pipe.ts     //用来写自定义pipe

 

pipe-name.pipe.ts

transform(value: any,args?: any):any{

       //transform是方法名

//第一个参数value 是带过滤的内容

       //第二个参数是第一个参数处理的条件,也就是参数

}

例如:

filter.pipe.ts

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

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {

  transform(subject: any, cource: any): any {
    if (!cource) {
      return subject;
    }
    return subject.filter(function (subjects) {
      return subjects.toLowerCase().includes(cource.toLowerCase());   //实现模糊查询
    });
  }
}

这个管道的作用是搜索包含关键字的内容

猜你喜欢

转载自blog.csdn.net/xnh_565175944/article/details/82115710
今日推荐