File

projects/maplander/shared/src/lib/components/country-code/country-code.directive.ts

Implements

AfterViewInit OnDestroy

Metadata

Selector [libCountryCode]

Index

Properties
Methods
Outputs

Constructor

constructor(_document: any, _ref: ElementRef, _service: CountryCodeService)
Parameters :
Name Type Optional
_document any No
_ref ElementRef No
_service CountryCodeService No

Outputs

countrySelected
Type : EventEmitter<CountryCode>

Methods

ngAfterViewInit
ngAfterViewInit()
Returns : void
ngOnDestroy
ngOnDestroy()
Returns : void
Private onEvents
onEvents()
Returns : void
Private openComponent
openComponent()
Returns : void

Properties

Private _dialogCountryRef
Type : MatDialogRef<CountryCodeComponent | CountryCode>
import {AfterViewInit, Directive, ElementRef, EventEmitter, Inject, OnDestroy, Output} from '@angular/core';
import {DOCUMENT} from '@angular/common';
import {CountryCodeService} from './country-code.service';
import {CountryCode} from '@maplander/types';
import {MatDialogRef} from '@angular/material';
import {CountryCodeComponent} from '../country-code/country-code.component';

@Directive({
  selector: '[libCountryCode]'
})
export class CountryCodeDirective implements AfterViewInit, OnDestroy {

  @Output() countrySelected: EventEmitter<CountryCode>;
  private _dialogCountryRef: MatDialogRef<CountryCodeComponent, CountryCode>;

  constructor(
    @Inject(DOCUMENT) private _document: any,
    private _ref: ElementRef,
    private _service: CountryCodeService
  ) {
    this.countrySelected = new EventEmitter<CountryCode>();
  }

  ngAfterViewInit(): void {
    const tag = this._ref.nativeElement.tagName;
    if (tag === 'INPUT' || tag === 'TEXTAREA') {
      this._ref.nativeElement.addEventListener('focus', this.onEvents.bind(this));
      this._ref.nativeElement.addEventListener('keyup', this.onEvents.bind(this));
    }
  }

  ngOnDestroy(): void {
    this._ref.nativeElement.removeEventListener('focus', this.onEvents.bind(this));
    this._ref.nativeElement.removeEventListener('keyup', this.onEvents.bind(this));
  }

  private onEvents(): void {
    this._ref.nativeElement.blur();
    this.openComponent();
  }

  private openComponent(): void {
    if (this._dialogCountryRef) {
      return;
    }
    this._dialogCountryRef = this._service.open();
    this._dialogCountryRef.afterClosed().subscribe((response: CountryCode) => {
      this._dialogCountryRef = null;
      if (response) {
        this._ref.nativeElement.value = `+${response.code}`;
        this.countrySelected.emit(response);
      } else {
        this.countrySelected.emit(null);
      }
    });
  }
}

result-matching ""

    No results matching ""