Is there a way to designate the current tab in PrimeNG's tabMenu as active?

Can someone please explain where I need to declare activeIndex variable and how to properly use it?

Here is my code in the HTML file:

<p-tabMenu [model]="tabMenuItems"></p-tabMenu>

And here is the TypeScript file:

tabMenuItems: MenuItem[];
private stateId: number;
private id: number;
...
ngOnInit() {
   this.tabMenuItems = [
        {label: 'Bar1', icon: 'ui-icon-insert-chart',
            command: (event: any) => {
                this.router.navigate(['/#', 
             this.id],{ queryParams: {'stateId': this.stateId} }); }
        },
        {label: 'Bar2', icon: 'ui-icon-date-range',
            command: (event: any) => {
                this.router.navigate(['/#', this.id],{ queryParams: {'stateId': this.stateId} }); }
        },
        {label: 'Bar3', icon: 'ui-icon-book',
            command: (event: any) => {
                this.router.navigate(['/#', this.id],
                    { queryParams: {'stateId': this.stateId} }); }
        },
        {label: 'Bar4', icon: 'ui-icon-help-outline',
            command: (event: any) => {
                this.router.navigate(['/#', this.id],
                    { queryParams: {'stateId': this.stateId} }); }
        },
        {label: 'Bar5', icon: 'ui-icon-public',
            command: (event: any) => {
                this.router.navigate(['/#', this.id],
                    { queryParams: {'stateId': this.stateId} }); }
        }
    ];

How can I ensure that each menu item activates the corresponding tab based on the activeIndex value?

Answer №1

Documentation

To set the [activeItem] property on the tabMenu, you can follow this example:

ngOnInit() {
   this.tabMenuItems = [
        {label: 'Bar1', icon: 'ui-icon-insert-chart',
            command: (event: any) => {
                this.router.navigate(['/#', 
             this.id],{ queryParams: {'stateId': this.stateId} }); }
        },
        {label: 'Bar2', icon: 'ui-icon-date-range',
            command: (event: any) => {
                this.router.navigate(['/#', this.id],{ queryParams: {'stateId': this.stateId} }); }
        },
        {label: 'Bar3', icon: 'ui-icon-book',
            command: (event: any) => {
                this.router.navigate(['/#', this.id],
                    { queryParams: {'stateId': this.stateId} }); }
        },
        {label: 'Bar4', icon: 'ui-icon-help-outline',
            command: (event: any) => {
                this.router.navigate(['/#', this.id],
                    { queryParams: {'stateId': this.stateId} }); }
        },
        {label: 'Bar5', icon: 'ui-icon-public',
            command: (event: any) => {
                this.router.navigate(['/#', this.id],
                    { queryParams: {'stateId': this.stateId} }); }
        }
    ];

    this.activeTab = this.tabMenuItems[1];
}

To implement this in HTML, use the following code:

<p-tabMenu [model]="tabMenuItems" [activeItem]='activeTab'></p-tabMenu>

Answer №2

Have you tried using ""routerLink:" instead of ""command:()=>"?

It's not necessary to manually assign the [activeItem], as routing should handle this automatically. However, if needed, you can assign it manually like this:

<p-tabMenu [model]="tabMenuItems" [activeItem]="tabMenuItems[0]"></p-tabMenu>

In a very simple example on StackBlitz, you'll notice that using the "command:()=>" option doesn't change the active tab when reloading or entering the URL manually. On the other hand, the "routerLink:" option works perfectly.

You may also find helpful information in this forum post on PrimeFaces.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having difficulty navigating the features of the rxjs `merge` interface

Having trouble with the RxJs merge interface: export function merge<A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): Observable<A[number]>; So, based on this information, I developed the following code const alpha ...

Having difficulty loading Angular2/ Tomcat resources, specifically the JS files

I am currently in the process of deploying my Angular2 web application on a Tomcat server. After running the ng build command, I have been generating a dist folder and uploading it to my Tomcat server. However, whenever I try to run my web app, I encounte ...

"Troubleshooting Typecscript and Angular: Dealing with mismatched argument

How can I resolve this Angular error: (response: HttpResponse<User>) => { which results in the following error message: Argument of type '(response: HttpResponse<User>) => void' is not assignable to parameter of type '(val ...

Execute the 'loadURL' function in the electron-Angular project when the Angular Compiler has finished preparing

When working with electron-Angular tutorials, it is common to create the window and load index.html from localhost after a set timeout. You'll often come across instructions similar to this: // set timeout to render the window not until the Angular c ...

Unable to locate the "lint" target for the project selected OR The data path "" must contain the necessary property 'lintFilePatterns'

Upon transitioning my Angular project structure to a monorepo setup as demonstrated in this tutorial, I encountered several configuration issues that required extensive troubleshooting to resolve. The first error message stated: Cannot find "lint" target ...

The DatePicker in Angular2 and Typescript is unable to execute the property 'toggle' because it is undefined

I've encountered an issue with the calendar icon for angular2's datepicker. Whenever I try to click on it, I keep getting this error: TypeError: Cannot read property 'toggle' of undefined at Object.eval [as handleEvent] (Admiss ...

Error encountered while fetching client credentials in Next-Auth Credential-Provider [next-auth]

Exploring the combination of nextjs and next-auth for authentication using a credential provider has been intriguing. However, I've encountered an issue when attempting to access a protected route while logged in: [next-auth][error][client_fetch_error ...

What is the best way to transfer values from an iterated object in HTML to a component in Angular 2/4?

My Angular2/4 app allows for file uploads to S3. The setup is such that when a user uploads a file, it will be stored in an S3 bucket. Once uploaded, the user will be shown the list of files they have uploaded. In case they upload the wrong file by mistake ...

Authenticating to Google APIs using Node.js within a lambda function: A step-by-step guide

I'm encountering an issue when trying to connect a Google sheet to an AWS Lambda function. While the code runs smoothly during local testing, upon deployment to the function, I receive an error message indicating that the credentials.json file cannot ...

Converting input tag to a method in component with uppercase transformation

Currently, this code resides within the <input tag I am looking to convert this code into a method in my component. Any ideas on how to do this? oninput="let p=this.selectionStart; this.value=this.value.toUpperCase(); this.setSelectionRange(p,p) ...

Enforcing type safety for mysql2 results in Typescript leads to robust data handling

I have been working on a project using NextJS and Typescript where I need to properly type my MySQL responses. This is the API endpoint I am working with: import { hash } from "bcrypt"; import type { NextApiRequest, NextApiResponse } from "n ...

Show a reset button in an Angular 2 reactive form only when the form has unsaved changes

I am working with a reactive form and need to add a reset button that will return the form values to their initial state. The reset button should only be visible if the form is dirty. Here is the form definition: this.form = new FormGroup({ firstName: ...

Mat-stepper in Angular Material causing binding errors

Trying to bind the parent mat-stepper component in order to check if the selected index is something, then do something else. It works but gives errors for each tab that is bound. The error message says it can't find property '0' of undefine ...

A step-by-step guide on sending a fetch request to TinyURL

I have been attempting to send a post request using fetch to tinyURL in order to shorten a URL that is generated on my website. The following code shows how I am currently writing the script, however, it seems like it's not returning the shortened URL ...

Navigating through unidentified object in Typescript

I'm working with an object that has an unknown format, specifically a users' CSV file. My task is to iterate through the keys to identify certain keys, such as phone numbers referenced as phoneNumbers1, phoneNumbers2, and so on in the .csv file. ...

Angular 2 Encounter Error When Trying to Access Undefined Property in a Function

Element: import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-ore-table', templateUrl: './ore-table.component.html', styleUrls: [&a ...

The Vue application is refusing to compile due to a syntax error caused by the presence of 'return' outside of a function

Upon attempting to run a build on my Vue app, I encountered the following syntax error. error in ./src/pages/Calendar.vue?vue&type=script&lang=ts& Syntax Error: 'return' outside of function. (175:4) 173 | getEventColor(event, Even ...

Ways to conceal the style tag in the view source similar to Angular Material

Is there a way to conceal the style tag from being visible in the view source? Take a look at the images I have uploaded to see what I am trying to achieve. See the style tag in the developer tool No style tag visible in the view source After running ng ...

Are all components in Next.js considered client components by default?

I have created a Next.js app using the app folder and integrated the Next Auth library. To ensure that each page has access to the session, I decided to wrap the entire application in a SessionProvider. However, this led to the necessity of adding the &apo ...

Ways to secure mat tab for verification

When clicking on a mat tab, I want it to display a warning asking if the user is sure. If the user selects yes, then the tab should change; otherwise, the user should remain on the same tab. However, currently, when I click on a tab, it changes before sh ...