How can I conditionally use either [href] or [routerLink] on an anchor?

后端 未结 5 1780
暖寄归人
暖寄归人 2021-01-01 11:56

I need for the same anchor link to be pointed conditionally locally or to external resource. I tried



        
5条回答
  •  臣服心动
    2021-01-01 12:15

    You can access routerLink instance by injecting RouterLinkWithHref in the directive.

    Directive:

    import { ElementRef, Optional, Input, Directive, OnChanges } from '@angular/core';
    import { RouterLinkWithHref } from '@angular/router';
    
    @Directive({
      selector: '[externalLink]'
    })
    export class ExternalLinkDirective implements OnChanges {
    
      @Input() externalLink: string;
    
      constructor(
        private el: ElementRef,
        @Optional() private link: RouterLinkWithHref
      ) {}
    
      ngOnChanges(){
    
        if (!this.link || !this.externalLink) {
          return;
        }
        this.el.nativeElement.href=this.link.href=this.externalLink;
    
        // Replace onClick
        this.link.onClick = (...args: any[]) => {
          return true;
        }
    
      }
    
    }
    

    Usage:

    
    Link
    

提交回复
热议问题