FFKL
1/9/2020 - 12:49 PM

pipe-onpush-change-detection.ts

import { ChangeDetectorRef, OnDestroy, Pipe, PipeTransform } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { get } from 'lodash';
import { Subscription } from 'rxjs';

import { ToursCatalog } from 'package-types';

@Pipe({
  name: 'departureCityLabel',
  pure: false
})
export class DepartureCityLabelPipe implements PipeTransform, OnDestroy {
  private onLangChange: Subscription;

  constructor(private translateService: TranslateService, private cd: ChangeDetectorRef) {}

  transform(value: ToursCatalog.DepartureSelector): string {
    if (!this.onLangChange) {
      this.onLangChange = this.translateService.onLangChange.subscribe(() => this.cd.markForCheck());
    }

    return get(value, `text.${this.translateService.currentLang}`);
  }

  ngOnDestroy(): void {
    if (this.onLangChange) {
      this.onLangChange.unsubscribe();
      this.onLangChange = null;
    }
  }
}