Reputation: 7067
Angular7, routerlink
to create a list of item clickable to navigate the corresponding detail page. 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. Fiddler shows no activity after the 1st click.
Routerlink in component:
<tr *ngFor="let item of Items">
<td><a routerLink="/itemdetail/{{item.id}}">{{item.id}}</a></td>
app-routing.module.ts
const routes: Routes =
[
...
{ path: 'itemdetail/:id', component: itemdetail}
];
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);
}
Upvotes: 1
Views: 694
Reputation: 1202
In your component you haven't used the one-way data binding on the routerLink
directive to update the links on the fly. Just add square-brackets around routerLink
directive for the links to update.
<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.
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. Click on the Item page
link in the preview screen to view the demo.
Upvotes: 1
Reputation: 505
ngOninit is not called again and again due to component being reused. Call the function getDetail inside the subscribe, After setting this.id as the subscription to activatedRoute will still be called after every successful navigation.
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);
}
Upvotes: 3