I want to open an external URL in a new tab from my Angular 8 SPA.
Answers to other questions suggest that you can use window.open(url, "_blank")
to achieve this, and this works for me, but I am looking for something I can unit test.
Based on an answer to a different question, I have tried injecting the Document
and calling document.open(url, "_blank")
like so:
import { Component, OnInit, Input, Inject } from "@angular/core";
import { DOCUMENT } from "@angular/common";
@Component( ........ )
export class MyClass implements OnInit {
private externalLink = "https://bbc.co.uk";
constructor(@Inject(DOCUMENT) private readonly document: Document) { }
ngOnInit() {
}
public navigate() {
this.document.open(this.externalLink, "_blank");
}
}
However, when this runs the screen goes immediately white and nothing else happens. No errors are logged to the console and placing a breakpoint in the method shows that the document is injected correctly as far as I can tell.
If this can't be resolved I am tempted to wrap a service around window.open()
and inject that.