NRaf
NRaf

Reputation: 7549

Default directives in Angular

I'm working on a shared sidebar component for my application that will be reused by a few modules.

Using the sidebar in the Users module, for example, might look like the following:

<sidebar>
  <sidebar-item title="Users"
                   icon="people"
                   routerLink="/users"
                   routerLinkActive="active"
                   [routerLinkActiveOptions]="{exact: true}"></sidebar-item>

  <sidebar-item title="Create User"
                   icon="add_circle"
                   routerLink="/users/create"
                   routerLinkActive="active"
                   [routerLinkActiveOptions]="{exact: true}"></sidebar-item>

  <sidebar-item title="Manage Users"
                   icon="edit"
                   routerLink="/users/manage"
                   routerLinkActive="active"
                   [routerLinkActiveOptions]="{exact: true}"></sidebar-item>
</sidebar>

This code will look pretty similar in other modules. Internally, the sidebar component is rendering it's children in an <ng-content> block gets access to the children using @ContentChildren.

What I'm trying to workaround is the need to specify routerLinkActive and routerLinkActiveOptions on each instance of sidebar-item. They're always going to be the same and for the styling to work, routerLinkActive needs to always be set to active.

Is there any way I can get this to work without needing to repeat those directives (either by setting a default value or by other means)?

Upvotes: 0

Views: 52

Answers (1)

Michael Kang
Michael Kang

Reputation: 52847

You could have the sidebar-item to be data-driven:

<sidebar-item *ngFor="let item of items" [title]="item.title"
               [icon]="item.icon"
               [routerLink]="item.link"
               routerLinkActive="active"
               [routerLinkActiveOptions]="{exact: true}"></sidebar-item>

Where items is:

[
   {  title: 'Users', icon: 'people', link:'/users' },
   {  title: 'Create User', icon: 'add_circle', link:'/users/create' },
   {  title: 'Manage Users', icon: 'edit', link:'/users/manage' }
]

Upvotes: 1

Related Questions