Michael Kang
Michael Kang

Reputation: 52847

Navigation to secondary route URL for routerLink attribute

Angular supports primary routes as string attributes.

i.e.

<button routerlink="/path1">Click Me!</button>

However, when there are multiple outlets, adding a secondary route does not work:

<button routerlink="/path1(foo:/path2)">Click Me!</button>  <<-- does not work

Is there a way to make this work?

Note: I realize its possible to achieve this with:

<a [routerLink]="['/path1', { outlets: { foo: '/path2' } }]">Click Me!</a>

My question is more about whether this is possible using plain string attributes (the router framework could parse it behind the scenes).

Upvotes: 1

Views: 669

Answers (1)

Max Koretskyi
Max Koretskyi

Reputation: 105497

It doesn't seem to be possible with the current implementation of the router. When you pass a string to a routerLink it gets wrapped into an array here:

@Directive({selector: ':not(a)[routerLink]'})
export class RouterLink {
  ...

  }

  @Input()
  set routerLink(commands: any[]|string) {
    if (commands != null) {
      this.commands = Array.isArray(commands) ? commands : [commands]; <---------------
    } else {
      this.commands = [];
    }
  }

And here is the function that tries to parse the wrapped commands and extract outlets from it:

function getOutlets(commands: any[]): {[k: string]: any[]} {
  if (!(typeof commands[0] === 'object')) return {[PRIMARY_OUTLET]: commands};
  if (commands[0].outlets === undefined) return {[PRIMARY_OUTLET]: commands};
  return commands[0].outlets;
}

As you can see, if the value inside the wrapped commands is not an object - which is your case, it always defaults to primary outlet and uses the value as a path for this primary outlet:

if (!(typeof commands[0] === 'object')) return {[PRIMARY_OUTLET]: commands};

Upvotes: 2

Related Questions