Var*_*run 61 typescript angular
我正在尝试在用户点击链接时打开新页面.我不能使用Angular 2路由器,因为它没有任何功能可以重定向到外部URL.
所以,我正在使用window.location.href ="...";
HTML代码:
<button (click)="onNavigate()">Google</tn-submenu-link>
Run Code Online (Sandbox Code Playgroud)
打字稿代码:
onNavigate(){
//this.router.navigateByUrl("https://www.google.com");
window.location.href="https://www.google.com";
}
Run Code Online (Sandbox Code Playgroud)
但是如何在新标签中打开它?什么时候使用window.location.href?
小智 95
onNavigate(){
window.open("https://www.google.com", "_blank");
}
Run Code Online (Sandbox Code Playgroud)
Sao*_*Biz 22
关于使用的一个警告window.open()是,如果传递给它的URL没有http://或https://在它前面,angular会将其视为路径.
要解决这个问题,请测试url是否以http://or 开头,https://如果不是则附加它.
let url: string = '';
if (!/^http[s]?:\/\//.test(this.urlToOpen)) {
url += 'http://';
}
url += this.urlToOpen;
window.open(url, '_blank');
Run Code Online (Sandbox Code Playgroud)
小智 9
在 HTML 中:
<a class="main-item" (click)="onNavigate()">Go to URL</a>
Run Code Online (Sandbox Code Playgroud)
或者
<button class="main-item" (click)="onNavigate()">Go to URL</button>
Run Code Online (Sandbox Code Playgroud)
在 TS 文件中:
onNavigate(){
// your logic here.... like set the url
const url = 'https://www.google.com';
window.open(url, '_blank');
}
Run Code Online (Sandbox Code Playgroud)
另一种可能的解决方案
const link = document.createElement('a');
link.target = '_blank';
link.href = 'https://www.google.es';
link.setAttribute('visibility', 'hidden');
link.click();
Run Code Online (Sandbox Code Playgroud)
为了更全面地解决这个问题,这是使用指令的另一种方法:
import { Directive, HostListener, ElementRef } from "@angular/core";
@Directive({
selector: "[hrefExternalUrl]"
})
export class HrefExternalUrlDirective {
constructor(elementRef: ElementRef) {}
@HostListener("click", ["$event"])
onClick(event: MouseEvent) {
event.preventDefault();
let url: string = (<any>event.currentTarget).getAttribute("href");
if (url && url.indexOf("http") === -1) {
url = `//${url}`;
}
window.open(url, "_blank");
}
}
Run Code Online (Sandbox Code Playgroud)
那么就像这样使用它一样简单:
<a [href]="url" hrefExternalUrl> Link </a>
Run Code Online (Sandbox Code Playgroud)
并且不要忘记在模块中声明该指令。
你可以在你的打字稿代码中这样做
onNavigate(){
var location="https://google.com",
}
Run Code Online (Sandbox Code Playgroud)
在您的 html 代码中添加一个锚标记并传递该变量(位置)
<a href="{{location}}" target="_blank">Redirect Location</a>
Run Code Online (Sandbox Code Playgroud)
假设你有网址像这样www.google.com没有http,你是不是被重定向到指定的网址,然后添加http://到location这样的
var location = 'http://'+ www.google.com
Run Code Online (Sandbox Code Playgroud)
如果您在 URL 中有绝对部分,我想与您分享另一种解决方案
SharePoint 解决方案与 ${_spPageContextInfo.webAbsoluteUrl}
HTML:
<button (click)="onNavigate()">Google</button>
Run Code Online (Sandbox Code Playgroud)
打字稿:
onNavigate()
{
let link = `${_spPageContextInfo.webAbsoluteUrl}/SiteAssets/Pages/help.aspx#/help`;
window.open(link, "_blank");
}
Run Code Online (Sandbox Code Playgroud)
并且 url 将在新选项卡中打开。
| 归档时间: |
|
| 查看次数: |
109605 次 |
| 最近记录: |