Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 RC6 pipes. Can I declare a pipe within the same .ts file as my component?

Tags:

angular

Do I have to register every single pipe within @ngModule? I have one which is used by single specific component only. Would be nice to declare it right in the same file, so nothing else is aware about it. I believe that was possible before - just can't find the right syntax.

Thank you.

like image 491
rook Avatar asked Sep 04 '16 19:09

rook


People also ask

Can I use pipe in TS file?

use date pipe in component ts files In laterst version of Angular i.e., from version 6 we can directly use angular pipes's public methods inside the components to format the values. For example we use date pipe format method formatMethod in component file by importing it from the @angular/common as shown below.

Can I use pipe in component Angular?

It's easy to create custom pipes to use in your templates to modify interpolated values. You don't have to duplicate your code if you want to also use a pipe's functionality in a component class. All you have to do really is inject the pipe like a service and then call its transform method.

Can I use two pipes in Angular?

No Filter Pipe Or OrderBy Pipe: Luckily, now these two pipes are not available in Angular 2 and instead Angular allows us to write custom pipes so we can write the custom pipes according to the logic we like to use. So let's see how to create the custom pipes.


2 Answers

Every Pipe, Component and Directive must be declared in a Module. This is because the compiler relies on the module's declarations to parse templates. If it hasn't seen MyPipe in the module's declarations (or the declarations of an imported module), then it will not look for it nor recognize it when you use the pipe in the template

If it's important that no other component be able to see your Pipe, create a module that contains only the component that uses the pipe and the pipe itself, and do not export the pipe.

import { NgModule }      from '@angular/core';
import { CommonModule }  from '@angular/common';
import { MyPipe }        from './my.pipe';
import { MyComponent }   from './my.component';

@NgModule({
  imports:      [ CommonModule ],
  declarations: [ MyComponent, MyPipe ],
  exports:      [], // don't export what you want to keep private
  providers:    []
})
export class MyModule { }
like image 169
BeetleJuice Avatar answered Nov 23 '22 22:11

BeetleJuice


Since RC6, the pipes property has been removed from ComponentTypeMetadata , you have to register them in NgModule.

like image 36
zhimin Avatar answered Nov 23 '22 21:11

zhimin