user1015388
user1015388

Reputation: 1515

angular4 directive not working inside HTML SPAN tag

I have written a directive in angular4, which works on input fields. When I apply that on SPAN tag, it is not working. Can we apply the directives on SPAN TAG, or is there any work around.

<span dirTemp>45789</span>

dirTemp actually corrects the value to 45,789

import { Directive, HostListener, ElementRef, OnInit, AfterViewInit, AfterViewChecked, AfterContentChecked } from '@angular/core';
@Directive({
  // tslint:disable-next-line:directive-selector
  selector: '[dirTemp ]',
})

export class FormatterDirective implements AfterViewChecked {
  private el: HTMLInputElement;

  constructor(
    private elementRef: ElementRef,
    private cPipe: MyPipe
  ) {
    this.el = this.elementRef.nativeElement;
  }

  // ngOnInit() {
  //  this.el.value = this.cPipe.transform(this.el.value);
  // }

  ngAfterViewChecked(): void {
    this.el.value = this.cPipe.parse(this.el.value);
    this.el.value = this.cPipe.transform(this.el.value);
  }

  @HostListener('focus', ['$event.target.value'])
  onFocus(value) {
    console.log('in formatter directive:', value);
    this.el.value = this.cPipe.parse(value);
  }

  @HostListener('focusout', ['$event.target.value'])
  onFocusout(value) {
    this.el.value = this.cPipe.transform(value);
  }

}

Upvotes: 1

Views: 956

Answers (1)

X Pahadi
X Pahadi

Reputation: 7443

Workaround: span doesn't have value but has innerText or innerHTML. So, On ngOnInit you can do:

 ngOnInit() {
    if(this.el.tagName.toUpperCase() !== 'INPUT') {
      //  Apply your tranform here:
      var originalValue =  this.el.innerText;
      this.el.innerText = this.cPipe.transform(originalValue);
    }
  }

Upvotes: 2

Related Questions