I've a simple component as following where I am trying to get reference to the active element from it's template.
export class SidebarComponent {
@ViewChildren(RouterLinkActive) linkItems: QueryList<RouterLinkActive>;
ngAfterViewInit() {
let activeLink = this.linkItems.find(item => item.isActive);
console.log('Active link is');
console.log(activeLink); //this is undefined
}
}
And here is a simple template for above component.
<ul>
<li>
<a [routerLink]="['/app/link1']" routerLinkActive="active"> Link 1</a>
</li>
<li>
<a [routerLink]="['/app/link2']" routerLinkActive="active"> Link 2</a>
</li>
</ul>
The problem is I am not getting the active element from the template even though the style is applied to the element with active class. The same code worked with angular v2 but breaked in angular v4. What should I do to get the active element in angular v4?
I'd try
constructor(private router:Router) {}
...
let isLinkActive = this.linkItems.toArray()[0].isLinkActive(this.router);
let activeLink = this.linkItems.find(item => isLinkActive(item));
I assume your check just happens too early (when isActive is not yet set)
See also the code in https://github.com/angular/angular/blob/82417b3ca59aa2e5f41ee12db4cb18970b5b4f47/packages/router/src/directives/router_link_active.ts (lines 98, 108, 132)