I'm trying to modify a custom pipe to react when language changes. here is my custom pipe, which validate and transform date into correct format
import { ChangeDetectorRef, Pipe, PipeTransform } from '@angular/core';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import { DateTime } from 'luxon';
import { FormattingService } from '../formatting.service';
@Pipe({
name: 'datex',
pure: false
})
export class DatexPipe implements PipeTransform {
translatePipe: TranslatePipe;
constructor(private translate: TranslateService, private _ref: ChangeDetectorRef) {
this.translatePipe = new TranslatePipe(translate, _ref);
}
transform(value: DateTime, format: string = FormattingService.DATETIME_FORMAT): string {
if (!value || !value.isValid) {
return this.translatePipe.transform('N/A');
} else if (!DateTime.isDateTime(value)) {
// eslint-disable-next-line no-console
console.error(new TypeError('Provided value is of type: ' + typeof(value) + '. Required type: DateTime'));
return '';
}
if (value.year < 1970) {
value = value.plus({ years: 100 });
}
return value.toFormat(format);
}
}
in line
return this.translatePipe.transform('N/A');
is translation N/A into different languages, but it works only when the page is reloaded or language was set before page loaded. So i changed pipe into impure
pure: false
but with this option pipe reacts to any change detection and pipe is called way too many times. The goal I want to achieve is dynamic translation similar to Translate Pipe which one has settings pure: false, but called only when language is changed, not all of change detection. Some type of Impure restricted pipe.