[英]How to use directive for external link in angular?
我有一個 angular 8 應用程序。 並且有可能輸入鏈接。
但是你有兩種鏈接:
內部和外部。 與外部我的意思是在網站域之外。 例如: http : //www.ad.nl
然后,如果用戶單擊該鏈接,則必須將用戶重定向到具有該鏈接的其他選項卡。
但是你也可以有一個內部鏈接:像這樣: http://localhost:4200/gezondheid/Measurement/actieindex
但是鏈接必須在同一個選項卡中打開。
我有一個這樣的指令:
@Directive({
selector: '[appExternalLink]'
})
/**
* This directive is responsible for checking if in Activity the link is a external link - then it wil open
* in a seperate tab or is the link an internal(same domain) link, then it will open in the same tab
*/
export class ExternalLinkDirective {
@HostBinding('attr.rel') relAttr = '';
@HostBinding('attr.target') targetAttr = '';
@HostBinding('attr.href') hrefAttr = '';
@Input() href: string;
/**
* Check if liink is external or not
*/
ngOnChanges() {
this.hrefAttr = this.href;
if (this.isLinkExternal()) {
this.relAttr = 'noopener';
this.targetAttr = '_blank';
}
}
/**
* if link is external, then set the rel and target attributes
*/
private isLinkExternal() {
return !this.href.includes(location.hostname);
}
我像這樣將它注入到組件中:
<a appExternalLink
*ngIf="activity.link; else nolink"
[href]="activity.link">
<div class="todo-day-part-subject">{{ activity.subject }}</div>
<div class="todo-day-part-block">
<div class="todo-day-part-icon {{ getIcon(activity.type) }}"></div>
<div class="todo-day-part-content">
<div class="todo-day-part-text">{{ activity.text }}</div>
<div class="todo-day-part-time">{{ activity.beginDate | date: 'HH:mm' }}</div>
<div *ngIf="activity.link" class="todo-day-part-readmore">Bekijk</div>
<div *ngIf="activity.state === 'Done'" class="todo-day-part-status-signal">
<span class="fa fa-check-circle"></span>
</div>
</div>
</div>
</a>
但它現在適用於實習鏈接。 但是,如果鏈接是: http : //www.ad.nl,那么它將在同一個選項卡中打開,而不是在單獨的選項卡中。
那我必須改變什么?
謝謝
首先,對於內部鏈接,我想您不是指 angular 應用程序內的鏈接,因為為此您必須使用[routerLink]
。 如果它只是在 angular 應用程序之外但在同一域內的不同頁面,我相信您應該執行以下操作:
@Directive({
selector: 'a[appExternalLink]'
})
export class ExternalLinkDirective {
@HostBinding('rel')
rel = '';
@HostBinding('target')
target = '_self';
@Input()
@HostBinding('href')
href?: string;
ngOnChanges(changes: SimpleChanges) {
if (changes.href) {
const isExternal = this.isLinkExternal();
this.rel = isExternal ? 'noopener' : '';
this.target = isExternal ? '_blank' : '_self';
}
}
/**
* Check if link is external or not
*/
private isLinkExternal() {
return !(this.href || '').includes(location.hostname);
}
}
這基本上意味着,不要使用attr.
綁定,因為這在這種情況下不起作用:) 您需要更新屬性,而不僅僅是屬性。
我已經創建了一個簡單的示例,說明您還可以如何解決此任務
這個想法是為了防止鏈接標簽的默認行為並通過 javascript 解析路由。
此外,您不需要知道每次 ngOnChanges 觸發時的鏈接類型。 因此,您只能在點擊事件時檢查它並決定將客戶路由到哪里。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.