你会在所有指令中看到这一点:
当您使用括号时,这意味着您正在传递一个可绑定的属性(一个变量)。
<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 dynamicQueryParameter = '129';
public routerLinkVariable = "/home";
更新 [routerLink]
<a [routerLink]="[routerLinkVariable]"[queryParams]="{unit: dynamicQueryParameter}"></a>
当你想点击这个链接时,它会变成:
<a href="/home?unit=129"></a>