zoukankan      html  css  js  c++  java
  • ng2自定义管道

    一、管道的作用及本质

    作用:数据处理

    本质:公用的方法

    二、定义管道组件

    //summary.pipe.ts
    import { Pipe, PipeTransform } from '@angular/core'; @Pipe({
    name:
    'summary',
    // pure: false 管道默认为纯管道,如果加了pure:false 则为非纯管道
      // 纯管道只能检测纯变更(原始类型(String Number Boolean Symbol)值的更改,或者对对象引用(Date Array Function Object)的更改

    }) export class SummaryPipe implements PipeTransform { transform(value: number[], args: any[]): any{return value.reduce((prev,next)=>{prev + next}); //数组求和 } }

    三、module组件中引入管道

    //app.module.ts
    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { AppComponent } from './app.component';
    import { SummaryPipe} from './summary.pipe';
    
    @NgModule({
      imports: [
        BrowserModule,
        SummaryPipe    //管道引入
      ],
      declarations: [
        AppComponent
      ],
      bootstrap: [ AppComponent ]
    })
    export class AppModule { }

    四、组件中使用管道

    // app.component.ts
    import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <div><span *ngFor="let i of list" >{{i}}&nbsp;</span></div>
    <div>{{list | summary:value}}</div>
      //模板中使用管道
        <button (click)="addNum()">add 4</button>
      `,
      styleUrls:['./app.component.css']
    })
    export class AppComponent {
      list: number[] = [1,2,3];
      addNum() {
        this.list.push(4);
      }
    }

    五、页面效果

    1.纯管道

    点击按钮之后

    2.非纯管道

    点击按钮之后从图中可以看出,使用非纯管道实现了累加,而使用纯管道不能实现累加

    六、说明

    模板中可以在管道后面加冒号:如:

    <div>{{list | summary:value}}</div>

    这里的value则为传给管道的参数(args

  • 相关阅读:
    LibreOJ #507. 「LibreOJ NOI Round #1」接竹竿
    BZOJ 4590: [Shoi2015]自动刷题机
    luogu P3808 【模板】AC自动机(简单版)
    cogs 2569. [東方] 博丽灵梦 梦想妙珠
    codeforces 1C. Ancient Berland Circus
    BZOJ 4570: [Scoi2016]妖怪
    HDU 1392 Surround the Trees
    cogs 999. [東方S2]雾雨魔理沙
    Uva 10652 Board Wrapping
    AC日记——[Sdoi2008]Cave 洞穴勘测 bzoj 2049
  • 原文地址:https://www.cnblogs.com/sghy/p/7047728.html
Copyright © 2011-2022 走看看