首页 文章

Angular 2使用组件属性动态设置routerLink

提问于
浏览
6

我创建了一个组件,其中包含一个带有routerLink属性的元素,我想从使用该组件的模板中设置该属性 . 当我尝试这样做时,我收到错误消息'无法读取属性'未定义'的路径' .

我的组件看起来链接这个:

INFO-box.component.ts

import { Input, Component } from "@angular/core";
import { ROUTER_DIRECTIVES } from "@angular/router";

@Component({
    selector: "info-box",
    template: require("./info-box.component.html"),
    directives: [
        ROUTER_DIRECTIVES
    ]
})

export class InfoBoxComponent {
    @Input() routerLink: string;
    @Input() imageUrl: string;
}

INFO-box.component.html

<a [routerLink]="[routerLink]"> 
    <img src="{{imageUrl}}" width="304" height="236">
</a>

并且使用组件的模板看起来像这样:

<info-box [routerLink]="['/test']" [imageUrl]="['./testimage.jpg']"

如果我不添加routerLink一切正常 . 我的路由器配置似乎是正确的,因为当我直接添加到我的模板时,它也可以正常工作 . 谁能帮我这个?

Grt Marco

3 回答

  • 4

    你可以在html中使用这样的代码来动态创建url

    例如,您在路由器中的路径是 path:'destination/:id' 然后您可以像这样使用routerLink

    <div *ngFor = "let item of items">
     <a routerLink = "/destination/{{item.id}}"></a>
    </div>
    

    我希望我的回答有用

  • 9

    对于任何有这个问题的人使用Angular 2.4和

    import { AppRoutingModule } from './app-routing.module';

    app.module.ts 而不是 ROUTER_DIRECTIVES (不再需要)中,以下语法对我有用:

    <a [routerLink]="['item', item.id ]">Item</a>
    
  • 0

    假设你的数组看起来像:

    this.menuuItems = [
      {
        text: 'Tournament Setup',
        path: 'app-tournament'
      }];
    

    现在在你的html使用中

    <li *ngFor = "let menu of menuuItems">
         <span routerLink="/{{menu.path}}">
          <a>{{menu.text}}</a>
        </span>
        </li>
    

相关问题