【问题标题】:Angular 2 dynamically set routerLink using a component propertyAngular 2 使用组件属性动态设置 routerLink
【发布时间】:2016-11-07 07:23:30
【问题描述】:

我创建了一个组件,其中包含一个带有 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 马可

【问题讨论】:

标签: javascript angular angular2-routing angular2-template angular2-components


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    对于使用 Angular 2.4 和

    遇到此问题的任何人

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

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

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

    【讨论】:

      【解决方案3】:

      假设你的数组看起来像:

      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>
      

      【讨论】:

        猜你喜欢
        • 2019-10-20
        • 2021-10-29
        • 1970-01-01
        • 2017-05-20
        • 1970-01-01
        • 2017-01-27
        • 1970-01-01
        • 2017-07-08
        • 2016-07-04
        相关资源
        最近更新 更多