来自ngFor项的动态routerLink值给出错误“得到插值({{}})其中表达式是预期的”

问题描述 投票:35回答:5

我正在尝试根据组件中的动态项目集在指令中设置routerLink值。但Angular2引发了一个错误:

EXCEPTION: Template parse errors:
Parser Error: Got interpolation ({{}}) where expression was expected at column 1 in [ {{item.routerLink}} ] in AppHeader@5:40 ("
    <a *ngFor="let item of headerItems" [ERROR ->][routerLink]=" {{item.routerLink}} ">
      {{item.text}}
    </a>
"): Header@5:40

header.component.ts

import {Component} from '@angular/core';
import {ROUTER_DIRECTIVES} from '@angular/router-deprecated';

@Component({
  selector: 'app-header',
  templateUrl: './app/components/header/header.component.html',
  directives: [ROUTER_DIRECTIVES]
})
export class AppHeader {
  headerItems: Object[] = [];

  constructor() {
    this.headerItems.push(
      { classes: 'navLink', routerLink: ['/Home'], text: 'Home' }
    );
  }
}

header.component.html

<div id="HeaderRegion">
  <nav class="nav">
    <a *ngFor="let item of headerItems" [routerLink]=" {{item.routerLink}} ">
      {{item.text}}
    </a>
  </nav>
</div>
angular angular2-directives
5个回答
84
投票

你不能使用[]结合{{}}前者或后者

[routerLink]="item.routerLink"

应该做你想做的。

routerLink="{{item.routerLink}}"

item.routerLink.toString()绑定到routerLink财产。


5
投票

您还可以使用以下代码来传递包含某些文本的表达式。

<div *ngFor="let customer of customers">
   <a [routerLink]="'customer/'+customer.index">Link</a>
</div>

3
投票

你可以在这个时候找到答案,因为我删除{{}}解决了类似的问题。你的代码可能是

<a *ngFor="let item of headerItems" [routerLink]="item.routerLink">
  {{item.text}}
</a>

2
投票

这样的事情对我们有用:

<input type="checkbox" [id]="['btn.botStepState-'+i]" [(ngModel)]="btn.botStepState" name="btn.botStepState-{{i}}" (change)="changeHandler($event)" class="cbx hidden" />
  • 属性绑定,即[]需要[]来评估值
  • 模型绑定,即[()]没有什么特别之处
  • 插值即{{}}可以与一般属性一起使用
  • 事件绑定,即()功能很好

0
投票

我有一个如何使你的路线动态的例子

在你的HTML组件中

<ul class="nav side-menu">
                <li *ngFor="let data of dataPermiso;let i= index">
                  <a><i class="{{data.icono}}"></i> {{data.categoria}} <span class="fa fa-chevron-down"></span></a>
                  <ul class="nav child_menu">
                    <li *ngFor="let item of data.permisoList;let a = index">
                      <a [routerLink]="item.ruta">{{item.titulo}}</a>
                    </li>
                  </ul>
                </li>
</ul>

在你的组件ts

  public dataPermiso:any[] = [];

  constructor(private loginserv: LoginService) {
    this.loadPermiso();
  }



  ngOnInit() {

  }

  public loadPermiso(){
    this.loginserv.listPermisos(this.dataStorage.idrol).subscribe((data)=>{
      this.dataPermiso= data;
    });
  }
© www.soinside.com 2019 - 2024. All rights reserved.