ChenLee
ChenLee

Reputation: 1499

Attribute directive @Input alias in Angular 2

I am learning attribute directives in Angular 2. When using @Input alias in attribute directives, It will not work, why?

component

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

directive

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;
  }

}

Upvotes: 2

Views: 2423

Answers (2)

eko
eko

Reputation: 40647

The notation should be like this:

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

with the brackets

Assuming the selector is:

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

  constructor(private el: ElementRef) { }

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

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

Upvotes: 4

RemyaJ
RemyaJ

Reputation: 5526

From angular docs -

<p HighlightDirective [appHighlight]="inputtedColor">text to highlight</p>

Upvotes: 1

Related Questions