Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger pipe reload without change in input

I am creating a TranslationPipe in angular 2 that takes a string as input and gets a translation from a TranslationService and returns it to the view. Like this for example:

<div>{{ 'hello world' | translate }}</div>
becomes:
hej verden

I want a way to change the language of a view, and update all the text on the page without reloading the whole page. Is there a way to trigger a reload of all TranslationPipes on a page, or even all pipes in an app?

Typically the only way a pipe is triggered in angular is by a change in the variable being passed to it. The input is a string though so instead I need to manually cause a trigger.

The text object storing all the translation text is stored in the service so I know an alternative solution would be to do this <div> translationObject['hello world'] </div> but that has less readability for the designer.

like image 254
andykais Avatar asked Apr 14 '16 13:04

andykais


2 Answers

With pure: false the pipe is evaluated each time Angular runs change detection.

@Pipe({
  name: 'xxx',
  pure: false
})

Consider this to be rather expensive.

An alternative way would be to pass the language as additional parameter, then Angular would evaluate the pipe also when the language changes.

like image 59
Günter Zöchbauer Avatar answered Nov 02 '22 04:11

Günter Zöchbauer


Pipes can have params, and even if you don't need them (or not all of them) their changing triggers pipe transform function.

// html
<p class="time-stamp">{{message.sent | timeAgo:trigger}}</p>

// component
trigger: number = 0;

ngOnInit() {
  setInterval(() => this.trigger = Math.random(), 60 * 1000)
}
like image 21
georgiy.zhuravlev Avatar answered Nov 02 '22 04:11

georgiy.zhuravlev