zoukankan      html  css  js  c++  java
  • 在angular中自定义筛选管道

    Angular 内置了一些管道,比如 DatePipe、UpperCasePipe、LowerCasePipe、CurrencyPipe 和 PercentPipe。 它们全都可以直接用在任何模板中;但是在angular(angular2)中由于性能的原因官方没有提供有关筛选和排序的管道,于是当我们在使用*ngFor需要筛选数据时可以自定义筛选管道。

    • in component
    filterargs = {title: 'hello'};
    items = [{title: 'hello world'}, {title: 'hello kitty'}, {title: 'foo bar'}];
    
    • in template
    <li *ngFor="let item of items | myfilter:filterargs">
    
    • in pipe
    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
        name: 'myfilter',
        pure: false
    })
    export class MyFilterPipe implements PipeTransform {
        transform(items: any[], filter: Object): any {
            if (!items || !filter) {
                return items;
            }
            // filter items array, items which match and return true will be
            // kept, false will be filtered out
            return items.filter(item => item.title.indexOf(filter.title) !== -1);
        }
    }
    
    • in app.module.ts; you no longer need to register the pipes in your @Component
    import { MyFilterPipe } from './shared/pipes/my-filter.pipe';
    
    @NgModule({
        imports: [
            ..
        ],C
        declarations: [
            MyFilterPipe,
        ],
        providers: [
            ..
        ],
        bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    参考链接:

    https://stackoverflow.com/questions/34164413/how-to-apply-filters-to-ngfor

  • 相关阅读:
    每天一道Java题[4]
    每天一道Java题[3]
    每天一道Java题[2]
    关于OOCSS架构
    新blog开张!
    [原]C++拾遗
    mark
    今天的情况(也是10月份的总结)
    11月份的总结
    Linux管道编程实例
  • 原文地址:https://www.cnblogs.com/yuanchao-blog/p/11527554.html
Copyright © 2011-2022 走看看