Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to re-trigger all pure pipes on all component tree in Angular 2

Tags:

I have pure pipe TranslatePipe that translates phrases using LocaleService that has locale$: Observable<string> current locale. I also have ChangeDetectionStrategy.OnPush enabled for all my components including AppComponent. Now, how can I reload whole application when someone changes language? (emits new value in locale$ observable).

Currently, I'm using location.reload() after user switches between languages. And that's annoying, because whole page is reloaded. How can I do this angular-way with pure pipe and OnPush detection strategy?

like image 548
EwanCoder Avatar asked Jan 26 '17 08:01

EwanCoder


People also ask

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 ).

What are impure pipes in angular 2?

Impure pipes in angular are the pipes that execute when it detects an impure change in the input value. An impure change is when the change detection cycle detects a change to composite objects, such as adding an element to the existing array.

What is pipe in angular7?

Pipe takes integers, strings, arrays, and date as input separated with |. It transforms the data in the format as required and displays the same in the browser. Let's see an example using pipes. Here, we display the title text in upper and lower case by using pipes.


1 Answers

Pure pipes are only triggered when the input value changes.

You could add an artificial additional parameter value that you modify

@Pipe({name: 'translate'}) export class TranslatePipe {   transform(value:any, trigger:number) {     ...   } } 

and then use it like

<div>{{label | translate:dummyCounter}}</div> 

Whenever dummyCounter is updated, the pipe is executed.

You can also pass the locale as additional parameter instead of the counter. I don't think using |async for a single pipe parameter will work, therefore this might a bit cumbersome (would need to be assigned to a field to be usable as pipe parameter)

like image 153
Günter Zöchbauer Avatar answered Sep 27 '22 21:09

Günter Zöchbauer