[英]RouterLink not updating target component after first click
Angular7, routerlink
to create a list of item clickable to navigate the corresponding detail page. Angular7,
routerlink
创建一个可点击的项目列表以导航相应的详细信息页面。 It works at the first click as expected, but all subsequent click won't update the detail, even their id
values are unique, detail page not being updated.它在第一次点击时按预期工作,但所有后续点击都不会更新详细信息,即使它们的
id
值是唯一的,详细信息页面也不会更新。 Fiddler shows no activity after the 1st click.第一次点击后 Fiddler 没有显示任何活动。
Routerlink in component:组件中的路由器链接:
<tr *ngFor="let item of Items">
<td><a routerLink="/itemdetail/{{item.id}}">{{item.id}}</a></td>
app-routing.module.ts app-routing.module.ts
const routes: Routes =
[
...
{ path: 'itemdetail/:id', component: itemdetail}
];
itemdetail.ts itemdetail.ts
id: string;
ngOnInit(): void
{
this.route.paramMap.subscribe((params: ParamMap)=>
{
this.id = params.get('id');
})
this.getDetail();
}
getDetail(): void
{
this.mySvc.getDetail(this.id)
.subscribe(data => this.items = data);
}
ngOninit is not called again and again due to component being reused.由于组件被重用,ngOninit 不会一次又一次地被调用。 Call the function getDetail inside the subscribe, After setting this.id as the subscription to activatedRoute will still be called after every successful navigation.
在subscribe里面调用getDetail函数,设置this.id作为对activateRoute的订阅后,每次导航成功后仍会调用。
id: string;
ngOnInit(): void
{
this.route.paramMap.subscribe((params: ParamMap)=>
{
this.id = params.get('id');
this.getDetail();
})
}
getDetail(): void
{
this.mySvc.getDetail(this.id)
.subscribe(data => this.items = data);
}
In your component you haven't used the one-way data binding on the routerLink
directive to update the links on the fly.在您的组件中,您没有使用
routerLink
指令上的单向数据绑定来动态更新链接。 Just add square-brackets around routerLink
directive for the links to update.只需在
routerLink
指令周围添加方括号即可更新链接。
<tr *ngFor="let item of Items">
<td><a [routerLink]="'/itemdetail/' + item.id">{{item.id}}</a></td>
<!-- other elements -->
</tr>
This way your link also updates when the item object changes.这样,您的链接也会在项目对象更改时更新。 Also call your
getDetails()
method inside params subscription, as shown below, so that your item details are updated in the template.还可以在 params 订阅中调用您的
getDetails()
方法,如下所示,以便在模板中更新您的项目详细信息。
id: string;
ngOnInit(): void
{
this.route.paramMap.subscribe((params: ParamMap)=>
{
this.id = params.get('id');
this.getDetail();
});
}
I have created a demo Stackblitz app to show the routerLink data binding approach.我创建了一个演示 Stackblitz 应用程序来展示 routerLink 数据绑定方法。 Click on the
Item page
link in the preview screen to view the demo.单击预览屏幕中的
Item page
链接以查看演示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.