I am facing an issue with navigation in my Angular application. I have two components and I want to navigate from the first component to the second, specifically to a particular pills tab, but it is not working as expected.
Initially, this is what gets displayed:
<!-- Error Modal -->
<div id="errorModal" class="modal modal-show" *ngIf="showModal">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Access Denied</h5>
</div>
<div class="modal-body">
<p>{{ modalErrorMessage }}</p>
<div class="mt-4 button-container">
<button class="btn btn-lg btn-primary" (click)="navigateToMyAccount(); $event.preventDefault()">Go Back</button>
</div>
</div>
</div>
</div>
Upon clicking on the button triggering the navigateToMyAccount()
function, we execute the following code for navigation:
navigateToMyAccount(): void {
this.router.navigate(['/my-account'], { queryParams: { tab: 'subscription' } });
}
In the second component, where we want to navigate, I utilize the following logic:
export class MyAccountComponent implements OnInit {
...
@ViewChild('nav', { static: true }) nav!: NgbNav;
async ngOnInit(): Promise<void> {
this.route.queryParams.subscribe(params => {
if (params['tab'] === 'subscription') {
this.gotoSubscriptionTab();
}
});
...
public gotoSubscriptionTab() {
console.log('gotoSubscriptionTab called');
if (this.nav) {
console.log('nav is defined', this.nav);
this.nav.select(2);
} else {
console.error('nav is not defined');
}
}
In the template of the second component, the navigation element looks like this:
<ul ngbNav class="nav-pills dark-nav-pills mb-3" #nav="ngbNav">
...
<li id="account" [ngbNavItem]="1">
...
<li id="subscription" [ngbNavItem]="2">
Despite various attempts, the navigation still fails with the error message:
nav is not defined
appearing in the browser's console. How can I ensure that the navigation works correctly from the first component to the specified ngbNavItem in the second component? I initially suspected a lifecycle problem, but even implementing AfterViewInit
did not resolve the issue...
Thank you for your help!