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

}
6
  • Renamed input property? What did you mean by that? Commented Apr 14, 2017 at 5:37
  • @RemyaJ input alias in Angular 2 Commented Apr 14, 2017 at 5:41
  • this.highlight(null) ?? How can you set a background as null ? It should be ' transparent' right? Commented Apr 14, 2017 at 5:43
  • @RemyaJ This is not the point. I am reading the document here angular.io/docs/ts/latest/guide/attribute-directives.html Commented Apr 14, 2017 at 5:45
  • Yes. You should have put property binding brackets. Commented Apr 14, 2017 at 5:46

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

From angular docs -

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

3 Comments

Your answer is wrong, OP did not share the directives selector in the question and class name will give an error that it's not bindable to p since it's not a known property if selector is something else.
How can you give input without specifying where to pass the input to. Ok. Now you edited. Now its right
Yes I made it in the plunker but forgot to add it in my answer :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.