[routerLink]和routerLink之间的区别

时间:2016-12-28 22:42:12

标签: angular routes routerlink angular-routerlink

[routerLink]routerLink之间有什么区别?你应该如何使用每一个?

4 个答案:

答案 0 :(得分:112)

您将在所有指令中看到这一点:

使用括号时,表示您传递了可绑定属性(变量)。

  <a [routerLink]="routerLinkVariable"></a>

所以这个变量(routerLinkVariable)可以在你的类中定义,它应该有如下的值:

export class myComponent {

    public routerLinkVariable = "/home"; // the value of the variable is string!

但是对于变量,你有机会让它变得动态吗?

export class myComponent {

    public routerLinkVariable = "/home"; // the value of the variable is string!


    updateRouterLinkVariable(){

        this.routerLinkVariable = '/about';
    }

如果没有括号,您只能传递字符串,而且您无法更改它,它会被硬编码,并且在整个应用中都会像这样。

<a routerLink="/home"></a>

更新:

使用专门针对routerLink的括号的另一个特点是,您可以将动态参数传递给您导航到的链接:

所以添加一个新变量

export class myComponent {
        private dynamicParameter = '129';
        public routerLinkVariable = "/home"; 

更新[routerLink]

  <a [routerLink]="[routerLinkVariable,dynamicParameter]"></a>

如果您想点击此链接,它将变为:

  <a href="/home/129"></a>

答案 1 :(得分:13)

假设你有

const appRoutes: Routes = [
  {path: 'recipes', component: RecipesComponent }
];

<a routerLink ="recipes">Recipes</a>

这意味着单击Recipes超链接将跳转到http://localhost:4200/recipes

假设参数为1

<a [routerLink] = "['/recipes', parameter]"></a>

这意味着将动态参数1传递给链接,然后导航到 http://localhost:4200/recipes/1

答案 2 :(得分:0)

路由器链接

不带方括号的routerLink-简单说明。

routerLink =和[routerLink]之间的区别主要是相对路径和绝对路径。

类似于href,您可能需要导航到./about.html或https://your-site.com/about.html

使用不带方括号的符号时,您将浏览相对和不带参数的

my-app.com/dashboard/client

my-app.com/dashboard 跳转到 my-app.com/dashboard/client

<a routerLink="client/{{ client.id }}" .... rest the same

在将routerLink和方括号一起使用时,您将执行应用程序以浏览绝对路径,并可以添加参数以了解新链接的困惑

首先,它不会包含从仪表板/到仪表板/客户端/客户端ID的“跳转”,并为您带来客户端/客户端ID的数据,这对于EDIT CLIENT更为有用

<a [routerLink]="['/client', client.id]" ... rest the same

routerLink的绝对方式或括号要求您进一步设置组件和app.routing.module.ts

进行测试时,没有错误的代码将“告诉您更多/ []的目的”。只需选择是否使用[]即可。比起您可能会尝试使用选择器(如上所述),它有助于动态路由。

Angular.io Selectors

看看什么是routerLink构造

  

https://angular.io/api/router/RouterLink#selectors

答案 3 :(得分:0)

路由器链接指令:

[routerLink]="link"                  //when u pass URL value from COMPONENT file
[routerLink]="['link','parameter']" //when you want to pass some parameters along with route

 routerLink="link"                  //when you directly pass some URL 
[routerLink]="['link']"              //when you directly pass some URL
相关问题