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

后端 未结 5 1760
暖寄归人
暖寄归人 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:04

    The simplest way would be to use *ngIf / else:

    
      External
    
    
    
      Internal
    
    

    EDIT#1: (Ugly workaround)

    Since you don't want to use *ngIf (I still don't understand why), you can do this:

    Template:

    Link
    

    Component:

    handleClick(outside: boolean, internalUrl: string, internalId: string, externalUrl: string): void {
      if (outside) {
        window.location.href = externalUrl;
        // You can also use Location class of Angular
      } else {
        this.router.navigate([`${internalUrl}/${internalId}`]);
      }
    }
    

提交回复
热议问题