Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to override the built-in Angular 2 pipes so they can be used globally?

Tags:

angular

I would like to override the "date" pipe and enjoy the benefit of global access everywhere just like the built-in pipe--aka, avoid having to import and use pipes[] array in every component annotation. Is this possible?

like image 360
Alan Lindsay Avatar asked Jan 27 '16 17:01

Alan Lindsay


People also ask

Can we chain more than one pipes in Angular?

We can chain multiple pipes together.

Which of the following are valid built in pipes in Angular?

Angular 7 provides some built-in pipes: Lowercasepipe. Uppercasepipe. Datepipe.

Are Angular pipes pure by default?

By default, pipes are defined as pure so that Angular executes the pipe only when it detects a pure change to the input value. A pure change is either a change to a primitive input value (such as String , Number , Boolean , or Symbol ), or a changed object reference (such as Date , Array , Function , or Object ).


1 Answers

Yes, you can use PLATFORM_PIPES to add a custom pipe and name that pipe date to hijack it.

@Pipe({
   name : 'date' // Hijacks the 'date' pipe
})
class CustomDatePipe {
  transform(val, args) {
    return /* do something new with the value */;
  }
}

@Component({
  selector: 'my-app',
  template : '{{mydate | date}}',
})
export class App {
  mydate = Date.now();
}

// Provides the CustomDatePipe globally
bootstrap(App, [provide(PLATFORM_PIPES, {useValue: [CustomDatePipe], multi: true})]);

This way you won't have to add specify it every time in pipes property in your components.

Here's a plnkr with an example working.

like image 94
Eric Martinez Avatar answered Oct 08 '22 20:10

Eric Martinez