Fra*_*ssi 2 angular2-pipe angular
情况:
我只需要在一个组件中使用管道.出于这个原因,我不想全局导入它,而只是在组件中导入它.
我试过寻找如何做的参考,但找不到它.
这是我的尝试:
管道:
当全球测试工作正常
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any
{
let keys = [];
for (let key in value)
{
keys.push({key: key, value: value[key]});
}
return keys;
}
}
Run Code Online (Sandbox Code Playgroud)
组件:
import { Component, NgModule } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import {CommonModule} from "@angular/common";
import { KeysPipe } from './keys.pipe';
@Component({
selector: 'page-attendees',
templateUrl: 'attendees.html'
})
@NgModule({
declarations: [ KeysPipe ],
imports: [ CommonModule ],
exports: [ KeysPipe ]
})
export class AttendeesPage {
public attendeeList = [];
public arrayOfKeys;
constructor(
public navCtrl: NavController,
public navParams: NavParams
) {
this.attendeeList = this.navParams.get('attendeeList');
this.arrayOfKeys = Object.keys(this.attendeeList);
}
ionViewDidLoad() {
console.log('AttendeesPage');
}
}
Run Code Online (Sandbox Code Playgroud)
错误:
Unhandled Promise rejection: Template parse errors:
The pipe 'keys' could not be found
Run Code Online (Sandbox Code Playgroud)
PLUNKER:
https://plnkr.co/edit/YJUHmAkhAMNki2i6A9VY?p=preview
问题:
你知道我做错了什么或者我错过了什么吗?
谢谢!
您声明了两个,NgModules并且您的管道仅在第二个模块中声明.但您的组件已声明为第一个模块.这就是它无法找到你的管道的原因.
这是您的Plunkr的更新(和工作版本):https://plnkr.co/edit/P3PmghXAbH6Q2nZh2CXK ? p = preview
编辑1:比较
以下是您之前所拥有的内容(删除了相关代码):
@NgModule({
declarations: [ KeysPipe ],
imports: [ CommonModule ],
exports: [ KeysPipe ]
})
@Component({
selector: 'my-app',
template: `
<li *ngFor="let attendee of attendeeList | keys">
{{ attendee.value.name }}
</li>
`,
})
export class App {
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)
这是工作版本:
//our root app component
@Component({
selector: 'my-app',
template: `
<li *ngFor="let attendee of attendeeList | keys">
{{ attendee.value.name }}
</li>
`,
})
export class App {
}
@NgModule({
imports: [ BrowserModule, CommonModule ],
declarations: [ App, KeysPipe ],
bootstrap: [ App ]
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)
请注意,您有2个NgModules.我只使用了一个,移除了另一个,我添加了管道declarations.
| 归档时间: |
|
| 查看次数: |
10308 次 |
| 最近记录: |