美文网首页
管道Angular 4 - Pipes

管道Angular 4 - Pipes

作者: 易则知 | 来源:发表于2018-08-16 13:57 被阅读149次

    在本章中,我们将讨论Angular 4中的管道。管道早先在Angular1中称为过滤器,在Angular 2和4中称为管道。
    它以整数、字符串、数组和日期作为输入,以|分隔,按需要转换格式,并在浏览器中显示相同的格式。

    内置的管道

    Angular 4提供了一些内置的管道。下面列出了管道

    • Lowercasepipe
    • Uppercasepipe
    • Datepipe
    • Currencypipe
    • Jsonpipe
    • Percentpipe
    • Decimalpipe
    • Slicepipe
    内置管道的使用示例
    import { Component } from '@angular/core';
    
    @Component({
       selector: 'app-root',
       templateUrl: './app.component.html',
       styleUrls: ['./app.component.css']
    })
    
    export class AppComponent {
       title = 'Angular 4 Project!';
       todaydate = new Date();
       jsonval = {name:'Rox', age:'25', address:{a1:'Mumbai', a2:'Karnataka'}};
       months = ["Jan", "Feb", "Mar", "April", "May", "Jun",
                 "July", "Aug", "Sept", "Oct", "Nov", "Dec"];
    }
    

    模板中使用

    <!--The content below is only a placeholder and can be replaced.-->
    <div style = "width:100%;">
       <div>
          <h1>Uppercase Pipe</h1>
          <b>{{title | uppercase}}</b><br/>
          
          <h1>Lowercase Pipe</h1>
          <b>{{title | lowercase}}</b>
          
          <h1>Currency Pipe</h1>
          <b>{{6589.23 | currency:"USD"}}</b><br/>
          <b>{{6589.23 | currency:"USD":true}}</b> //Boolean true is used to get the sign of the currency.
          
          <h1>Date pipe</h1>
          <b>{{todaydate | date:'d/M/y'}}</b><br/>
          <b>{{todaydate | date:'shortTime'}}</b>
          
          <h1>Decimal Pipe</h1>
          <b>{{ 454.78787814 | number: '3.4-4' }}</b> // 3 is for main integer, 4 -4 are for integers to be displayed.
       </div>
       
       <div>
          <h1>Json Pipe</h1>
          <b>{{ jsonval | json }}</b>
          <h1>Percent Pipe</h1>
          <b>{{00.54565 | percent}}</b>
          <h1>Slice Pipe</h1>
          <b>{{months | slice:2:6}}</b> 
          // here 2 and 6 refers to the start and the end index
       </div>
    </div>
    

    运行结果


    自定义管道

    app.sqrt.ts

    import {Pipe, PipeTransform} from '@angular/core';
    @Pipe ({
       name : 'sqrt'
    })
    export class SqrtPipe implements PipeTransform {
       transform(val : number) : number {
          return Math.sqrt(val);
       }
    }
    

    要创建自定义管道,我们必须从Angular/core导入管道和管道转换。在@Pipe指令中,我们必须给管道命名,它将在.html文件中使用。因为我们正在创建sqrt管道,所以我们将它命名为sqrt。

    随着我们进一步深入,我们必须创建类,类名是SqrtPipe。这个类将实现PipeTransform

    类中定义的transform方法将以参数作为数字,并在取平方根后返回数字。

    因为我们已经创建了一个新文件,所以我们需要在app.module.ts中添加相同的内容。

    <h1>自定义管道</h1>
    <b>Square root of 25 is: {{25 | sqrt}}</b>
    <br/>
    <b>Square root of 729 is: {{729 | sqrt}}</b>
    

    运行结果



    相关文章

      网友评论

          本文标题:管道Angular 4 - Pipes

          本文链接:https://www.haomeiwen.com/subject/shvnbftx.html