您现在的位置:首页 >> 前端 >> 内容

Angular学习笔记之管道概念、Angular的常用内置管道讲解

时间:2018/1/25 14:59:36 点击:

  核心提示:概念处理原始值到显示值的转换如:{{date | date:yyyy-MM-dd hh-mm-ss}}将原始值 Wed Jan 24 2018 21:20:53 GMT+0800 (中国标准时间) 通...

概念

处理原始值到显示值的转换

如:

{{date | date:'yyyy-MM-dd hh-mm-ss'}}

将原始值 Wed Jan 24 2018 21:20:53 GMT+0800 (中国标准时间) 通过date管道 转化成 2018-01-24 09-20-53

Angular的常用内置管道

uppercase 转换成大写英文

//html:
大写转换{{myName|uppercase}}
//ts:
myName:string = 'Baobab';
//输出BAOBAB

lowercase 转换成小写英文

//html:
小写转换{{myName|lowercase }}
//ts:
myName:string = 'Baobab';
//输出baobab

date 日期格式化,带有可选参数

Angular学习笔记之管道概念、Angular的常用内置管道讲解

number

Angular学习笔记之管道概念、Angular的常用内置管道讲解

自定义管道

执行命令 ng g pipe xxx,注意管道需要在module中的declaration中声明

demo一:将原始数字放大n倍

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

@Pipe({
  name: 'multiple'
})
//带有元数据的装饰类@pipe,定义了管道的名字

export class MultiplePipe implements PipeTransform {

  transform(value: any, args?: any): any {
    if(!args){
        args = 1;       
    }
    return value*args;
  }

}

//transform(value: any, args?: any),value代表原始值,args可选参数

使用管道multiple

//html
将数字4放大3倍{{numberTest|multiple:3}}
//ts
numberTest:number = 4;

demo二:过滤器

假设现在有一个原始对象列表list,写一个过滤器,过滤出符合输入文字(假设对象的name属性值是变量keyword)的对象

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

@Pipe({
  name: 'stockfilter'
})
export class StockfilterPipe implements PipeTransform {

  transform(list: any[], filed:string , keyword: any): any {
    if(!keyword || !filed){
        return list;
    }
    let keyItem = list.filter(item=>{
        return item[filed].indexOf(keyword)>= 0
    })
    return keyItem ;

  }

}

transform(list: any[], filed:string , keyword: any):原始值list,可选参数有两个,一个是元素属性,一个是元素属性值,返回符合条件的对象。

使用管道

Tags:AN NG GU UL 
作者:网络 来源:BAOBAB_cc的