I have a variable that have either
/my/internal/route
https://externalroute.ch
.On the first option, I'll just route to the target pages, which is lazy loaded.
On the second, I'll open it into a new page.
I've tried to to do it like this
<a [routerLink]="url" [target]="url.includes('https') ? '_blank' : '_self'">my link</a>
and to follow this idea
But none of them worked.
I need to make my website crawlable by the google SEO bots. It's the reason why I haven't done it with a method.
Maybe the example added in the example do works, but it wasn't for me. maybe because I'm running the website through an Iframe.
But I did come with a solution that add the correct attributes, depending if I have another host name or not. It is the best solution I could come up with.
import { isPlatformBrowser } from '@angular/common'
import { Directive, ElementRef, HostBinding, Inject, Input, PLATFORM_ID } from '@angular/core'
@Directive({
selector: 'a[href]',
})
export class ExternalLinkDirective {
@HostBinding('attr.rel') relAttr = null
@HostBinding('attr.target') targetAttr = null
@HostBinding('attr.href') hrefAttr = ''
@Input() href: string
constructor(@Inject(PLATFORM_ID) private platformId: string, private elementRef: ElementRef) {}
ngOnChanges() {
this.hrefAttr = this.href
if (this.isLinkExternal()) {
this.relAttr = 'noopener'
this.targetAttr = '_blank'
this.elementRef.nativeElement.addEventListener('click', () => {
window.open(this.href, '_blank', 'noopener')
})
}
}
private isLinkExternal() {
return (
this.href?.includes('http')
)
}
}
Thx to this article which give me the code