Angular 2 Links To External URLs Treated As Relative Paths For Routing

6.9k views Asked by At

I've created a component which receives properties set on it's selector:

<app-navigation-card
        label="My Label"
        description="Description of Item"
        type="download"
        [links]="[{path:'https://somedomain.com/somefile.zip', label:'Download'}]"
></app-navigation-card>

The inputs are set up in the NavigationCard class:

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-navigation-card',
  templateUrl: './navigation-card.component.html',
  styleUrls: ['./navigation-card.component.scss']
})
export class NavigationCardComponent implements OnInit {

  @Input() label: String;
  @Input() description: String;
  @Input() links: Object;
  @Input() type: String;

  constructor() { }

  ngOnInit() {
  }

}

In the template:

<div class="label">{{label}}</div>
<div class="description">{{description}}</div>
<ul *ngIf="links != undefined" class="links">
  <li *ngFor="let link of links" [routerLink]="link.path">
    <span *ngIf="type == 'download'"><a href="{{link.path}}">{{link.label}}</a></span>
    <span *ngIf="type == 'navigation'" [routerLink]="link.path"><{{link.label}}</span>
    <div></div>
  </li>
</ul>

If type == navigation, the router redirects to the correct component, but when it's a download, I'm getting this error:

EXCEPTION: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'style-guide/https%3A/somedomain.com/somefile.zip'

This URL works fine when explicitly entered in the href of a link but not via property binding. Any idea how to remedy this?

2

There are 2 answers

2
Pankaj Parkar On BEST ANSWER

You should consider creating an anchor tag as its seems to be an external URL which going to download a file. Rather remove *ngIf and just have 1st elements of *ngFor without span wrapper.

Additionally remove routerLink added to li element, which is getting fired the router.navigate function because of event bubbling.

<li *ngFor="let link of links">
    <a [attr.href]="link.path">{{link.label}}</a>
</li>

Or else have a click event & call function from controller, and open path in new tab using window.open(path). It will automatically download the file.

0
Nicolás Garitagoitia On

You can add https:// before the variable.

<a [attr.href]="'https://' + link.path">{{link.label}}</a>

Angular will recognize this as an absolute path, and redirect you to the URL.