Search code examples
angularangular-router

How to add a conditional routing between href and routerlink in angular


I have a variable that have either

  1. /my/internal/route
    or
  2. 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.

Requirement

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.


Solution

  • 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.

    1. Creating a directive
    2. Listening on change
    3. Analyzing if the url does contain the same namespace as the actual website.
    4. If not, add the required attributes & subscribe to the on click listener because for me the default one wasn't working
    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