2

Angular router's [routerLink] directive adds CSS class router-link-active to active link. I'd like to write directive based on this class.

import { Directive, ElementRef} from '@angular/core';
@Directive({selector: '.router-link-active'})
export class HighlightDirective {
    constructor(el:ElementRef) {
        el.nativeElement.style.backgroundColor = 'yellow';
    }
}

However it doesn't work as I expect.

It works if directive is hard coded in template:

<a class="router-link-active">Feature1</a>

but it doesn't work when css class is added dynamically by routerLink:

<a [routerLink]="['/feature1']">Feature1</a>

Although CSS class is added, directive code is not fired.

These are my very first steps with Angular2, so maybe the solution is easy, but I cannot find the answer.

akn
  • 3,712
  • 26
  • 43

1 Answers1

0

That's not supported. Angular2 instantiates components and directives only to selectors that match HTML statically added to a components template. Anything dynamic is ignored (HTML added using [innerHTML]="..." or attributes or classes added dynamically.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567