Skip to content Skip to sidebar Skip to footer

How Can I Change The Routing In Angular From Outside The Scope Of The Angular Application?

My question title might be a bit confusing, so hopefully the following details will clear it up. Essentially, the navigation bar is out of my control and it is written in just plai

Solution 1:

If someone is looking for a potential solution, here's a solution I was recommended in another forum. Maybe there's a better way to do it and improve upon it, but here's what I have so far:

In app.component.ts (or wherever you want to handle routing):

declare var window: any;

//@Component stuff...
export class AppComponent implements OnInit, OnDestroy {

    routerSubject: Subject<string> = new Subject<string>();

    constructor(private router: Router) {
        // Assign the observable to the window object, so that we can call it from outside
        window.routerSubject = this.routerSubject;
    }

    ngOnInit() {
        this.routerSubject.subscribe((url: string) => {
            // Programmatically navigate whenever a new url gets emitted.
            this.router.navigate([`/${url}`]);
        });
    }

    ngOnDestroy() {
        this.routerSubject.unsubscribe();
    }
}

Now, in index.html:

<body>
    <header>
        <!-- Emit a new value on click, so that Angular (which has already been subscribed) can programmatically route -->
        <a onclick="window.routerSubject.next('home');">Home</a>
        <a onclick="window.routerSubject.next('about');">About</a>
    </header>
    <app-root></app-root>
</body>

Obviously, you can put your onclick method in a seperate JS file, and put the Angular routing logic in a service, etc etc. But this is the general gist of the solution I came up with.

Either way, this should enable people to route an Angular app from the outside.


Solution 2:

If you are using the latest angular2 version you can use routerLink as shown below:

 <a routerLink="/home" routerLinkActive="my-link-active-css-class">Home</a>

The documentation is pretty good: https://angular.io/docs/ts/latest/guide/router.html


Post a Comment for "How Can I Change The Routing In Angular From Outside The Scope Of The Angular Application?"