大家好,我是 Angular 2 的新手,我正在尝试创建自定义管道/过滤器,
但是当我想注入(inject)我在 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;
}
}
});
}
}
}
测试.组件.html
<input type="text" [(ngModel)]="filterText">
<ul>
<li *ngFor="let todo of todos | filter: filterText ">
{{todo}}
</li>
</ul>
最佳答案
您应该如下将Pipe注入(inject)到相应的模块中,并在组件中使用它
declarations: [
Filter
]
关于javascript - Angular 2 管道依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42924138/