While working on Angular 6, I found that there is no way to use constant typescript file for routes path

Viewed 309

e.g. Let's say I have a home component

home.component.html, home.component.ts

and in home.component.html file, I have anchor link to be routed

<a id="routeDashboard" [routerLink]="['/dashboard']">Dashboard</a>

So what I want is - Instead of hardcoding route path directly here, can we have some constant route path file, i.e. referenced from html file.

1 Answers

Check Angular RouterLink, your code should be either:

<a id="routeDashboard" [routerLink]="['/dashboard']">Dashboard</a>

or

<a id="routeDashboard" routerLink="/dashboard">Dashboard</a>

Quote from the document:

If the link is static, you can use the directive as follows: routerLink="/user/bob">link to user component

You can write the links in a constant file or home.component.ts file home.component.ts

links = [
    {id: 'routeDashborad', path: '/dashboard, name: 'Dashboard'},
    {id: 'routeProfile', path: '/profile', name: 'Profile'}
]

home.component.html

<div *ngFor="let link of links">
    <a [id]="link.id" [routerLink]="[link.path]">{{ link.name }}</a>
</div>

Added:

if we put links in a file constants.ts

export class Constants {
    public static links = [{...}]
}

You can import it into home.component.ts file:

import { Constants } from '/path/to/constants/file';

links = Constants.links;
Related