How can I know, on the first page load, what the current route is, from within a directive?
Not sure if this is a bug, or I'm not configuring things correctly. I have a directive that gets a Router injected. I listen for router.onRouteStart
events, and when I initially reload the page, a routeStart event is not fired. I do get routeStart events when I manually trigger route changes.
My directive looks like:
@NgDirective(
selector: '[current-route]'
)
class CurrentRoute {
Router router;
Element element;
CurrentRoute(this.element, this.router) {
toggleActive();
router.onRouteStart.listen((e) {
toggleActive();
});
}
bool isRoute() {
print(router.activePath);
print(router.root);
if (router.activePath.isEmpty) return false;
return element.attributes['current-route'] == router.activePath.first.name;
}
void toggleActive() {
if (isRoute()) {
element.classes.add('active');
} else {
element.classes.remove('active');
}
}
}
When I first
print(router.activePath); // empty list
print(router.root); // null
Basically, I want to set a CSS class on an element if that element matches the current route. I'm guessing a directive with a Router is the way to go, but maybe there's something better.
Maybe you need to wait for the routing to complete:
var subscription;
subscription = router.onRouteStart.listen((e) {
subscription.cancel();
e.completed.then((_) {
toggleActive();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With