How to redirect to an external URL in Angular2? How to redirect to an external URL in Angular2? angular angular

How to redirect to an external URL in Angular2?


You can use this-> window.location.href = '...';

This would change the page to whatever you want..


An Angular approach to the methods previously described is to import DOCUMENT from @angular/common (or @angular/platform-browser in Angular< 4) and use

document.location.href = 'https://stackoverflow.com';

inside a function.

some-page.component.ts

import { DOCUMENT } from '@angular/common';...constructor(@Inject(DOCUMENT) private document: Document) { }goToUrl(): void {    this.document.location.href = 'https://stackoverflow.com';}

some-page.component.html

<button type="button" (click)="goToUrl()">Click me!</button>

Check out the platformBrowser repo for more info.


The solution, as Dennis Smolek said, is dead simple. Set window.location.href to the URL you want to switch to and it just works.

For example, if you had this method in your component's class file (controller):

goCNN() {    window.location.href='http://www.cnn.com/';}

Then you could call it quite simply with the appropriate (click) call on a button (or whatever) in your template:

<button (click)="goCNN()">Go to CNN</button>