Angular 中的动态 routerLink
Dynamic routerLink in Angular
我有一个列表,其中包含字符串,在这个列表中我使用 *ngFor 没问题。我在 ngFor 中使用索引来确定走哪条路线,但我发现了这种设计的缺陷,所以我想改变它。在列表组件中,我有一个字符串数组,就像列表项一样。我如何使用索引路由到此列表的内容。
我现在的代码是这样的:
<div class="col-md-12">
<ul class="list-group">
<a
class="list-group-item"
routerLinkActive="active"
style="cursor: pointer;"
[routerLink]="[i]"
*ngFor="let l of list; let i = index" >
{{ l }}
</a>
</ul>
</div>
我想实现这样的目标:
<div class="col-md-12">
<ul class="list-group">
<a
class="list-group-item"
routerLinkActive="active"
style="cursor: pointer;"
[routerLink]="[id[i]]"
*ngFor="let l of list; let i = index" >
{{ l }}
</a>
</ul>
</div>
此列表的 component.ts 如下所示:
@Input() list: string[] = [];
@Input() urls: string[] = [];
@Output() btnpress = new EventEmitter<string>();
id: string[] = [];
constructIdList() {
this.urls.forEach(url => {
if(url.length > 0) {}
let tmp = url.split('/');
if(tmp.length > 0) {
console.log(tmp.pop());
}
});
}
添加方法应该可以解决问题:
TS
getRoute(ndx: number): string {
return "[" + id[ndx] + "]";
}
HTML
[routerLink]="getRoute(i)"
我有一个列表,其中包含字符串,在这个列表中我使用 *ngFor 没问题。我在 ngFor 中使用索引来确定走哪条路线,但我发现了这种设计的缺陷,所以我想改变它。在列表组件中,我有一个字符串数组,就像列表项一样。我如何使用索引路由到此列表的内容。
我现在的代码是这样的:
<div class="col-md-12">
<ul class="list-group">
<a
class="list-group-item"
routerLinkActive="active"
style="cursor: pointer;"
[routerLink]="[i]"
*ngFor="let l of list; let i = index" >
{{ l }}
</a>
</ul>
</div>
我想实现这样的目标:
<div class="col-md-12">
<ul class="list-group">
<a
class="list-group-item"
routerLinkActive="active"
style="cursor: pointer;"
[routerLink]="[id[i]]"
*ngFor="let l of list; let i = index" >
{{ l }}
</a>
</ul>
</div>
此列表的 component.ts 如下所示:
@Input() list: string[] = [];
@Input() urls: string[] = [];
@Output() btnpress = new EventEmitter<string>();
id: string[] = [];
constructIdList() {
this.urls.forEach(url => {
if(url.length > 0) {}
let tmp = url.split('/');
if(tmp.length > 0) {
console.log(tmp.pop());
}
});
}
添加方法应该可以解决问题:
TS
getRoute(ndx: number): string {
return "[" + id[ndx] + "]";
}
HTML
[routerLink]="getRoute(i)"