[英]How to create and call a pipe from the component in Angular 2?
我想創建一個動態管道,我將從組件中調用它。
import {Component, Pipe, PipeTransform} from 'angular2/core';
@Pipe({ name: 'filter', pure: false })
export class filter implements PipeTransform {
transform(value) {
this.items1=value;
this.ticket1 = [];
if (this.items1.length >0) {
for (var i = 0; i < this.items1.length; i++) {
this.ticket1.push(this.items1[i])
}
}
}
}
我想從組件調用這個管道。
您需要在組件的pipes
屬性中指定它
@Component({
pipes: [ filter ]
})
export class MyComponent {
(...)
}
並在您的模板中使用它:
{{someArray | filter}}
<div *ngFor="someArray | filter">(...)</div>
編輯
如果要在組件類中直接調用管道,則需要實例化它並調用其tranform
方法:
@Component({
(...)
})
export class MyComponent {
constructor() {
let filterPipe = new filter();
let arr = [ ... ];
var fiteredArr = filterPipe.transform(arr);
}
(...)
}
在 rc6 版本中,您需要在模塊中注冊要使用的管道 -> 聲明
@NgModule({
declarations: [
AppComponent ,
filter
]....
我只是想添加到@pasha-oleynik 的答案中。 Angular 2+ 包括 Ionic 2+ 都希望在模塊中聲明管道:
@NgModule({
declarations: [
AppComponent ,
filter
]
這也是唯一需要聲明管道的地方。 模塊或組件下不再有管道屬性。
您需要注冊要在組件中使用的管道:
@Component({
...
pipes: [filter],
template: `
<div *ngFor="let item of someData | filter">{{item}}</div>
`
...})
class SomeComponent {
someData = [ ... ];
}
@NgModule({
imports: [CommonModule],
declarations: [filter]
})
export class MyFilterModule()
為了使管道可用,將模塊添加到要使用它的地方的導入
@NgModule({
declarations: [AppComponent, SomeComponent],
imports: [BrowserModule, MyFilterModule]
})
export class AppModuleModule()
如果你想從代碼中調用管道
let f = new filter();
f.transform(value, filterArg);
如果您想在不同的模塊上多次使用您的管道,我建議您將所有管道聚合到一個模塊中(例如PipesAggrModule
),然后將該模塊導入所需的模塊。 例如:
my-pipe.module.ts
@Pipe({name: 'MyPipe'})
export class MyPipe { ... }
pipes-aggr.module.ts
:
@NgModule({
imports: [
CommonModule
],
exports: [
...
MyPipe,
MyPipe2,
...
],
declarations: [..., MyPipe, MyPipe2, ...]
})
export class PipesAggrModule {}
然后,要使用您的管道,只需將導入PipesAggrModule
導入所需的模塊。
my.module.ts
@NgModule({
imports: [
CommonModule,
PipesAggrModule
],
...
}
export class MyModule {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.