0

This is the ngOnInit in the componet.ts file

ngOnInit() {
      this.locationService.getLocation().subscribe( locations => {
      this.locations = locations;
    });
  }
<a [routerLink]="['/locations-list']">

when I use a [routerLink] to navigate to the above component it navigates to the component and load the view, but it does not trigger above ngOnInit method. But if I refresh the page it works fine.
Is there any fix for above problem.

Already I used href to navigate to pages and with href above method works fine always but its very slow. That's why I changes href to [routerLink].

This is the component.html that contains the view

                <div class="table-responsive">
                  <table class="table">
                    <thead class=" text-primary">
                      <th>
                        Location Name
                      </th>

                    </thead>
                    <tbody *ngIf="locations?.length > 0">
                      <tr *ngFor="let location of locations">
                        <td *ngIf="location.verified != false">
                          {{location.locationName}}
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
Lahiru Mirihagoda
  • 1,113
  • 1
  • 16
  • 30

3 Answers3

3

ngOnInit() is only called once after a component is instantiated, but not when the route changes. You can inject the router and subscribe to it's events or params to get notified about route changes.

ngOnInit() {
     this.route.params.subscribe(params: any) => {
       if(params) //your code
    });
}
Seba Cherian
  • 1,755
  • 6
  • 18
1

when the router param changed, the base route stays the same. So it doesn't trigger the ngOnInit. So subscribe to the route event

ngOnInit() {
     this.route.params.subscribe(
     params => { 
            // your code
     });
  }
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
1

Try this

// on click call this function
    (click)="HyperLink()"
// on ts file 
    HyperLink(){
       window.open('/locations-list');  
   }
Syed Kashif
  • 420
  • 6
  • 13