在Angular 6上工作时,我发现无法对路径使用常量Typescript文件

时间:2019-06-29 04:19:09

标签: angular

例如假设我有一个home组件

home.component.html, home.component.ts

在home.component.html文件中,我有要链接的锚链接

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

所以我想要的是-而不是在这里直接对路由路径进行硬编码,我们可以有一些恒定的路由路径文件,即从html文件引用。

1 个答案:

答案 0 :(得分:3)

检查Angular RouterLink,您的代码应为:

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

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

文档引用:

  

如果链接是静态的,则可以使用如下指令:routerLink =“ / user / bob”>链接到用户组件

您可以将链接写入恒定文件或home.component.ts文件中 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>

已添加

如果我们将链接放在文件constants.ts中

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

您可以将其导入home.component.ts文件:

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

links = Constants.links;