美文网首页Angular.js专场程序员Web前端之路
Angular2 在component中pipe(管道)失效

Angular2 在component中pipe(管道)失效

作者: SuperBinlin | 来源:发表于2017-11-06 14:54 被阅读45次

    管道即获取数据输入,然后转换他,根据自己的逻辑得到期望的输出,和vue的过滤器类似,比如Date类型数据我们期望将他转换成人类能一眼就看明白的日期。

    最近在开发过程中,遇到了一个很奇葩的问题,我定义了一个管道,之前都是在页面中引用,并且运行良好,后来我需要在组件中使用该管道,结果居然没有任何效果...

    一般定义管道过程
    1.新建hello.pipe.ts

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({ 
      name: 'helloPipe' 
    })
    
    @Injectable()
    export class HelloPipe implements PipeTransform {
      transform(value: string) {
        return "HELLO "+value.toUpperCase();
      }
    } 
    

    2.在app.module.ts(根模块)中declarations声明模块内部成员

    import {NgModule} from '@angular/core';
    import {BrowserModule} from '@angular/platform-borwser';
    import {AppComponent} from './AppComponent';
    import { HelloPipe } from "hello.pipe.ts";
    
    @NgModule({
        declarations: [HelloPipe],
        imports: [BrowserModule],
        bootstrap: [AppComponent]
    })
    export class AppModule{}
    

    3.在模板中引用pipe

    <div>
       <p>{{ 'superBinlin' | helloPipe }}</p>  //output:HELLO SUPERBINLIN
    </div>
    

    在根模块声明的pipe在页面中引用有效,而在页面中引用的component中的模板则无效,这也是令我困惑的地方...

    寻求了一些解决方案,大多是要注意得在根模块中声明,于是我做了个尝试,将组件也写成一个功能模块,并在组件功能模块中申明pipe,结果很欣喜,组件中的pipe生效了。

    具体操作方法:
    只需新建组件功能模块,并在改模块中申明pipe,myComponent.module.ts

    import { NgModule } from '@angular/core';
    import { IonicPageModule } from 'ionic-angular';
    import { myComponent } from 'myComponent.ts';
    import { HelloPipe } from "hello.pipe.ts";
    
    @NgModule({
      declarations: [
        myComponent,
        HelloPipe
      ],
    
      imports: [
        IonicPageModule.forChild(myComponent)
      ],
    
      exports: [
        myComponent
      ]
    })
    
    export class MyComponent {}
    

    大功告成,组件的模板引用pipe得以生效.

    相关文章

      网友评论

      本文标题:Angular2 在component中pipe(管道)失效

      本文链接:https://www.haomeiwen.com/subject/jrparxtx.html