Use the window. location. replace() method to redirect to an external url in React, e.g. window. location.
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>
I think you need à target="_blank", so then you can use window.open
:
gotoGoogle() : void {
window.open("https://www.google.com", "_blank");
}
If you've been using the OnDestry lifecycle hook, you might be interested in using something like this before calling window.location.href=...
this.router.ngOnDestroy();
window.location.href = 'http://www.cnn.com/';
that will trigger the OnDestry callback in your component that you might like.
Ohh, and also:
import { Router } from '@angular/router';
is where you find the router.
---EDIT--- Sadly, I might have been wrong in the example above. At least it's not working as exepected in my production code right now - so, until I have time to investigate further, I solve it like this (since my app really need the hook when possible)
this.router.navigate(["/"]).then(result=>{window.location.href = 'http://www.cnn.com/';});
Basically routing to any (dummy) route to force the hook, and then navigate as requested.
in newer versions of Angular with window as an any
(window as any).open(someUrl, "_blank");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With