【问题标题】:Angular2 pipes dependency injectionAngular2管道依赖注入
【发布时间】:2017-03-21 10:16:15
【问题描述】:

大家好,我是 anguler 2 的新手,我正在尝试创建自定义管道/过滤器

但是当我想注入我在 app.ts 中创建的管道时,它不像附图中那样可行

我的组件代码:

import { Component, OnInit ,Pipe, PipeTransform} from '@angular/core';
import { Input, Injectable, ApplicationRef, ChangeDetectorRef } from '@angular/core';
import {Observable} from 'rxjs/Rx'
import {Filter} from '../filter.pipe';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css'],
  pipesp[Filter]

})

export class TestComponent implements PipeTransform  {
    private todos = ['wash dishes', 'Clean the ground','program the site', 'eat'];
  constructor() {
  }

   transform(value: any) {
    if (!value) {
      return '';
    }

  }
}

filter.pipe.ts 代码:

import  {Pipe, PipeTransform} from  '@angular/core';
@Pipe({name:'filter'})
export class Filter {
    transform(value,args){
        if(!args[0]){
            return value;
        }else if ( value){
            return value.filter(item => {
                for(let key in item){
                    if((typeof item[key] === 'string' || item[key] instanceof String) && (item[key].indexOf(args[0]) !==-1)){
                        return true;
                    }
                }
            });
        }
    }

}

test.component.html

<input type="text" [(ngModel)]="filterText">
<ul>
    <li *ngFor="let todo of todos | filter: filterText "> 
        {{todo}}
    </li>
</ul>

【问题讨论】:

    标签: javascript angular typescript pipes-filters


    【解决方案1】:

    你应该将管道注入到相应的模块中,并在组件中使用它

     declarations: [
        Filter
    ]
    

    【讨论】:

      【解决方案2】:

      您需要在 Ng 模块中包含管道组件(在根组件模块中)并在所有组件中全局使用它

      @NgModule({
        imports:      [ BrowserModule ],
        declarations: [ SearchPipe ],
        bootstrap:    [ AppComponent ]
      })
      

      直接在模板中使用

      @Component({
        selector: 'my-app',
        template: '<p>My name is <strong>{{ name | search}}</strong>.</p>', 
      })
      

      【讨论】:

      • 我没有使用引导程序,我使用的是 Matirla 设计
      • 我的解决方案与 bootstrap/MD 无关。我给你提供了如何正确添加管道的解决方案,以便你可以在任何地方使用它
      【解决方案3】:

      这是solution

      @Component({
        pipes: [ filter ] 
      })
      

      但不是

      @Component({
        pipes[Filter]
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-04-26
        • 2016-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-03
        相关资源
        最近更新 更多