javascript - Angular 2中的属性指令@Input别名

标签 javascript angular

我正在学习 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;
  ...

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

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

相关文章:

javascript - Bootstrap 切换多个元素上的文本更改

javascript - JQuery - 在页面加载时加载两个元素

angular - 如何使用 mat-dialog 的 backgroundClick 关闭对话框并将更改的数据发送回父组件

angular - ngrx reducer 在发送 Action 后不触发

android - Nativescript/Angular 中 NavigationButton 上的远程图像

javascript - 如何使用表单数据打印值?

JavaScript 将命名函数分配给变量

javascript - 使用 javascript 在表中动态追加一行

angular - Ag-grid:如何在使用 AggFunc 时更改定义列 headerName?

Angular 2 FormGroup动态添加验证器