Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I know, on the first page load, what the current route is, from within a directive (AngularDart)?

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.

like image 982
Seth Ladd Avatar asked Oct 01 '22 17:10

Seth Ladd


1 Answers

Maybe you need to wait for the routing to complete:

var subscription;
subscription = router.onRouteStart.listen((e) {
  subscription.cancel();
  e.completed.then((_) {
    toggleActive();
  });
});
like image 181
pavelgj Avatar answered Oct 05 '22 10:10

pavelgj