3

I'm trying to work with routerLink with external links. The links are exposed on index.html (that's like a menu from an external App), like this:

Index.html

<body>
  <div>
    <ul>
      <li><a onclick="window.changePage('home')" routerLink="/">Home</a>
      </li>
      <li><a onclick="window.changePage('info')" routerLink="/">Info</a>
      </li>
    </ul>
  </div>
  <app-root></app-root>
</body>

And the problem seems like angular doesn't load RouterModule when I access from this external links. If I navigate by this.router.navigate(....) this works fine. I put an example here: plunker

Step 1: Click on Home and in Go to Info button. You can see that "Go to Info" has a routerLink and you can click on it. Step 2: Refresh the page. Click on Info and you'll see that "Go to Info" can't be clicked it. How can I force angular load RouterModule with external links?

  • 2
    It's not supposed to. Just use a normal link instead of a `routerLink`. `routerLink` also won't work outside Angular components if you are using Angular 2/3/4. If you are using AngularJS 1.x, please change the `angular` tag to `angularjs`. – Günter Zöchbauer Aug 16 '17 at 11:14
  • I'm working with OP on this problem, I hope I can clarify. Our application's menu exists outside of our Angular 2/4 app as it may have to support some functional areas written with other frameworks (we agree this is a terrible approach, our bosses insist on it). We've got around this by exposing a method using `window['navigateApp'] = () => this.router.navigate`... and calling `window.navigateApp` onclick of menu links. The correct component is rendered, but routerLinks within the rendered component are left without any attributes and do not work – elf337 Aug 16 '17 at 11:35

2 Answers2

1

It is better to router that in your .ts file.

In the anchor tag ,just call the function window.changePage('home') and similarly window.changePage('info'),and

In .ts file inside the function navigate it.

-1

Update

Check the comments and other answer, the following is just a work around


@Günter Zöchbauer has already mentioned the solution in the comments

Change your info component as below

import { Component } from '@angular/core';

@Component({
  /* use href instead of routerlink*/
  template: `Info HTML
            <a href="/home">Go to Home</a>
  `,
})
export class InfoComponent {
  constructor() {
  }
}
Community
  • 1
  • 1
MJK
  • 3,434
  • 3
  • 32
  • 55
  • I agree this would work, but it would cause a complete reload of the entire app code on every menu click, which would negate the benefit of using an SPA framework like Angular – elf337 Aug 16 '17 at 11:36
  • Like @elf337 said, that will force a reload on the page and that's not what you should do on an Angular app. – Filipe Agrati Sep 05 '17 at 15:37