selector may be declared as one of the following:
ElementRef represents a location in a View that has an injection, change-detection and render context associated with it. (e.g. Component or Directive)
An ElementRef is created for each element in the template that contains a Directive, Component or data-binding.
import {Directive, ElementRef} from 'angular2/core';
@Directive({
selector: '[myHighlight]' // Notice the selector syntax for Attribute Direcitve
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}<div [highlight]>My content</div>@Directive({
selector: '[sgSample]',
host: {
'(mouseenter)': 'onMouseEnter()',
'attr.role': 'button'
}
})
class SampleDirective {
role = 'button';
onMouseEnter() {...}
}
@Directive({
selector: '[sgSample]'
})
class SampleDirective {
@HostBinding('attr.role') role = 'button';
@HostListener('mouseenter') onMouseEnter() {...}
}import {Directive, ElementRef, Input} from 'angular2/core';
@Directive({
selector: '[myHighlight]',
host: {
'(mouseenter)': 'onMouseEnter()',
'(mouseleave)': 'onMouseLeave()'
}
})
export class HighlightDirective {
constructor(private el: ElementRef) { }
onMouseEnter() { this._highlight("yellow"); }
onMouseLeave() { this._highlight(null); }
private _highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}export class HighlightDirective {
@Input('myHighlight') highlightColor: string;
private _defaultColor = 'red';
constructor(private el: ElementRef) { }
onMouseEnter() { this._highlight(this.highlightColor || this._defaultColor); }
onMouseLeave() { this._highlight(null); }
private _highlight(color:string) {
this.el.nativeElement.style.backgroundColor = color;
}
}<div hightlight="ligthblue">My Content</div>
<div [highlight]="'lightgreen'">My Content</div> <!-- Same -->import {Directive, Input, ElementRef, Renderer} from 'angular2/core';
@Directive({
selector: '[highlight]',
host: {
'(mouseenter)': 'onMouseEnter()',
'(mouseleave)' : 'onMouseLeave()'
}
})
export class HighlightDirective implements OnInit {
@Input('highlight') color: string;
constructor(private elementRef: ElementRef, private renderer: Renderer) {
}
onMouseEnter() {
this.highlightBackground(this.color);
}
onMouseLeave() {
this.highlightBackground(null);
}
private highlightBackground(color: string) {
this.renderer.setElementStyle(this.elementRef.nativeElement, "backgroundColor",
color);
}
}