Ionic2学习笔记(3):Pipe

时间:2021-07-10 07:48:59

作者:Grey

原文地址: http://www.cnblogs.com/greyzeng/p/5538630.html

Pipe类似过滤器,比如,在一个字符串要展现在页面之前,

我们需要对这个字符串进行一些操作,比如:将字符串转化为大写,加一个前缀/后缀……

Pipe的作用就是来实现类似的需求:

模型如下:

假设一个字符串: "hello", 我们在展示这个字符串的时候,需要先转换为大写,

然后加一个后缀 " WORLD", 最后字符串展示的效果是HELLO WORLD

Ionic2学习笔记(3):Pipe

因为需求比较简单,我们可以用一个Pipe来实现转大写和增加后缀的功能,

  • 进入项目:cd MyFirstApp
  • 新建一个名字为NewPipe的Pipe,

    命令:ionic g pipe NewPipe

    Ionic2学习笔记(3):Pipe

    项目目录会多出一个文件夹:

    Ionic2学习笔记(3):Pipe

  • 打开NewPipe.ts, 修改其中的transform方法

    Ionic2学习笔记(3):Pipe

  • 在../app/home/home.ts中引入这个Pipe

    Ionic2学习笔记(3):Pipe

  • 在../app/home/home.html中增加字符串显示:

    Ionic2学习笔记(3):Pipe

    在../app/home/home.ts中,设置字符串的值:

    Ionic2学习笔记(3):Pipe

  • 注入Pipe

    在../app/home/home.html中,

    Ionic2学习笔记(3):Pipe

    注意,这里的newPipe是这个名字:

    Ionic2学习笔记(3):Pipe

  • 运行,ionic serve -l

Ionic2学习笔记(3):Pipe

参考:

http://www.joshmorony.com/how-to-use-pipes-to-manipulate-data-in-ionic-2/

http://mcgivery.com/understanding-ionic-2-pipe/

------

上一篇:Ionic2学习笔记(2):自定义Component

下一篇:Ionic2学习笔记(4):*号