![](/img/trans.png)
[英]How to use Storybook with a component using [routerLink] (Angular)?
[英]Angular 2 dynamically set routerLink using a component property
我创建了一个组件,其中包含一个带有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
你可以在html中使用这样的代码来动态创建url。
例如,您在路由器中的path:'destination/:id'
是path:'destination/:id'
然后您可以像这样使用routerLink
:
<div *ngFor = "let item of items">
<a routerLink = "/destination/{{item.id}}"></a>
</div>
对于任何有这个问题的人使用Angular 2.4和
import { AppRoutingModule } from './app-routing.module';
在app.module.ts
而不是ROUTER_DIRECTIVES
(不再需要)中,以下语法对我ROUTER_DIRECTIVES
:
<a [routerLink]="['item', item.id ]">Item</a>
假设你的数组看起来像:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.