angular4指令在HTML SPAN标签内不起作用

时间:2018-07-17 14:57:25

标签: html angular

我用angular4编写了一条指令,该指令适用于输入字段。 当我将其应用于SPAN标签时,它无法正常工作。 我们可以在SPAN TAG上应用指令吗?还是可以解决此问题?

<span dirTemp>45789</span>

dirTemp实际上将值校正为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);
  }

}

1 个答案:

答案 0 :(得分:2)

解决方法:span没有value,但是有innerTextinnerHTML。因此,您可以在ngOnInit上进行以下操作:

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