Jeb50
Jeb50

Reputation: 7067

RouterLink not updating target component after first click

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

Answers (3)

Hu Chen
Hu Chen

Reputation: 1

might also be a problem of your ngOnDestroy(), mine was.

Upvotes: 0

Shravan
Shravan

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

Mohit Singh
Mohit Singh

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

Related Questions