我正在Angular 2中学习属性指令。在属性指令中使用@Input别名时,它将不起作用,为什么?

零件

<p appHighlight = "color">Hightlight Me</p>


指示

export class HighlightDirective {

  @Input('appHighlight') highlightcolor: string;

  constructor(
    // ElementRef is a service that grants direct access to the DOM element through its nativeElement property.
    private el: ElementRef
  ) {
    // el.nativeElement.style.backgroundColor = 'yellow';
  }


  // @HostListener decorator lets you subscribe to events of the DOM element that hosts an attribute directive
  @HostListener('mouseenter') onMouseEnter() {
    this.highlight(this.highlightcolor || 'red');
  }

  @HostListener('mouseleave') onmouseleave() {
    this.highlight(null);
  };

  private highlight(color: string) {
    this.el.nativeElement.style.backgroundColor = color;
  }

}

最佳答案

表示法应如下所示:

<p myHighlight [appHighlight]="color">Hightlight Me</p>


带括号

假设选择器是:

@Directive({
  selector: '[myHighlight]'
})
export class HighlightDirective {

  constructor(private el: ElementRef) { }

  @Input('appHighlight') highlightcolor: string;
  ...


插脚示例:http://plnkr.co/edit/vqZ4gjHc1KNFro62HlVJ?p=preview

关于javascript - Angular 2中的属性指令@Input别名,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43405691/

10-09 16:51