'Angular 2 pipe with variable parameter
I'm in the course of learning Angular2/Ionic2 so please excuse my ignorance. I got to learning Pipes and everything seemed easy until I stumbled on this problem. Let me demonstrate the problem using a perfect example with temperatures.
Say that I have pipe which return Celisus or Fahrenheit temperature value, depending on the setting saved on localStorage (Celsius is default input value).
So I created a Pipe which do this:
export class TemperatureConverterPipe implements PipeTransform {
// Selected temperature unit
private unit: string;
constructor(private settings: Settings){
// Get immediately the temperature unit from localStorage
// And subscribe to changes
this.settings.radio().subscribe(data => {
this.unit = data.temp_unit
});
}
// Return temperature
transform(value: number): number {
switch(this.unit){
case "c":
return value;
break;
case "f":
return celsiusToFahrenheit(value);
break;
default:
return value;
}
}
// Convert celsius temp to fahrenheit
celsiusToFahrenheit(value: number){
return value * 9/5 + 32;
}
}
Problems I'm stuck at:
- How this pipe can watch for parameter change (Temperature unit) and return the new values (e.q. C to F)? Because currently it only watches for Input (Temperature value) changes.
- Is this a correct way to solve this?
Thank you very much!
Solution 1:[1]
Pipe:
@Pipe(name: 'tempConverter')
export class TemperatureConverterPipe implements PipeTransform {
// Selected temperature unit
//private unit: string;
constructor(){
}
// Return temperature
transform(value: number,unit:string): number {
switch(unit){
case "c":
return value;
break;
case "f":
return celsiusToFahrenheit(value);
break;
default:
return value;
}
}
// Convert celsius temp to fahrenheit
celsiusToFahrenheit(value: number){
return value * 9/5 + 32;
}
}
HTML call:
[temperatureProperty]="value | tempConverter:unit"
Subscribe to the service in the ngOninit of calling component and pass unit.
Solution 2:[2]
You can make the pipe impure
@Pipe(name: 'tempConvert', pure: false)
export class TemperatureConverterPipe ...
this way the pipe is called every time change detection is run. With impure pipes you should ensure that the pipe doesn't do any expensive work because it will be called very often.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Suraj Rao |
| Solution 2 | Günter Zöchbauer |
