【问题标题】:angular4 directive not working inside HTML SPAN tagangular4 指令在 HTML SPAN 标记中不起作用
【发布时间】:2018-07-17 14:57:24
【问题描述】:

我在 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);
  }

}

【问题讨论】:

  • 您能否添加一些代码以便我们更好地帮助您?
  • 我添加了我的指令,可能我需要添加另一个主机监听器。我将该指令应用于表中的列。 TD 值在
  • 默认情况下跨度不会触发focusout。您应该发布您的 html 结构以获取有关您正在尝试做的事情的更多上下文
  • @Pierre,好的。我的html很简单,在一个表中,我有 45789

标签: html angular


【解决方案1】:

解决方法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);
    }
  }

【讨论】:

  • @user1015388 你已经在你的构造函数中定义了。 this.el = this.elementRef.nativeElement;
  • 我试过用这个,this.el.innerText 给出空值
  • 是的,我发现我在 SPAN TAG 中的价值在 {{}} 中是动态的。所以它是空的。我们怎样才能达到目标
  • 我需要使用 afterviewchecked,因为我的数据在视图完成后呈现。谢谢
猜你喜欢
  • 2018-12-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-02
  • 2014-04-22
  • 1970-01-01
  • 2018-09-17
  • 2016-06-06
  • 2018-10-14
相关资源
最近更新 更多