0
votes

I have two components : LinkGroup and LinkItem.

LinkItem's template is simple :

<a routerLinkActive="active"
   [routerLinkActiveOptions]="{exact: true}"
   [routerLink]="link"> {{ title }}
</a>

The components are used like this :

<link-group title="Users">
    <link-item title="..." link="...">
    <link-item title="..." link="...">
    <link-item title="..." link="...">
</link-group>

<link-group title="Servers">
    <link-item title="Server1" link="...">
    <link-item title="Server2" link="...">
    <link-item title="Server3" link="...">
</link-group>

If e.g. Server2 is clicked I want to catch the routerLinkActive change and emit it to the parent link-group component, so that I can change the title's ("Servers") style (to 'font-weight : bold').

I've looked at the directives page at https://angular.io/api/router/RouterLinkActive.

but since I'm fairly new to Angular4, I'm open to suggestions. Should I extend the 'RouterLinkActive' directive and override ngOnChanges ? (how??)

Or is there an even simpler way ?

Any help is appreciated.

Edit: I should have added the template for link-group :

<div routerLinkActive="active">{{ title }}
   <ng-content></ng-content>
</div>

Please note that all link-item components (and the actual links with their routerLink directives) are inside

Of course the css is present :

div.active { font-weight: bold }

Note: when I don't use components at all, in pure html + routerLink directive it works.

2

2 Answers

0
votes

Ok, I solved it like this :

link-group ts file :

active = '';
@ContentChildren(LinkItemComponent) linkItems: QueryList<LinkItemComponent>;



    ngAfterContentInit() {
        this.router.events.subscribe(event => {
          if (event instanceof NavigationStart) {
            const c: LinkItemComponent = this.linkItems.find(item => item.link === event.url);
            if (c)
              this.active = 'active';
            else
              this.active = '';
          }
        });
      }

Then simply added 'active' to the div's class attribute :

<div class="...  {{ active }}">{{ title }}
   <ng-content></ng-content>
</div>
-1
votes

I think the problem come from you have not the style for hyperlink tag when it's activating. You can try to add the style as:

.active {
  font-weight:bold;
  color:red;
}

A sample example for this at here

Hope this help!