What is the best way to retrieve the chosen item within a Tabmenu component in Primeng?

I have created a simple array of MenuItem objects to populate the Tabmenu component from Primeng. Here is an example:

.ts file:

items = MenuItem[];
activeItem = MenuItem;

//constructor, etc...

ngOnInit() {

    this.items = [
                {label: 'Homework', icon: 'fa-file-pdf-o'},
                {label: 'Movies', icon: 'fa-file-pdf-o'},
                {label: 'Games', icon: 'fa-file-pdf-o'},
                {label: 'Pictures', icon: 'fa-file-pdf-o'}
            ];
this.activeItem = this.items[2]
}

.html file:

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

To set the active item of the tabmenu, you can use the activeItem property like this:

this.activeItem = this.items[2]

Now, my question is whether it's possible to retrieve the activeItem on click. For example:

<p-tabMenu [model]="items" [activeItem]="activeItem" (click)="getActiveItem(...)"></p-tabMenu>

Method for getting Active Item:

getActiveItem(activeItem: MenuItem){
    this.activeItem = activeItem;
    console.log(activeItem);
    return this.activeItem;
  }

P.S. Here is a link to the TabMenu component from Primeng: CLICK

Answer №1

Utilize the command feature to incorporate tabs as part of the MenuModel API.

The command property defines the function to execute when an item is clicked.

this.items = [
   ...
  {label: 'Pictures', icon: 'fa-file-pdf-o', command: (event) => {
    //event.originalEvent: Browser event
    //event.item: menuitem metadata
  }}
];

Answer №2

To solve the issue, I tackled it by defining a new variable within the template that corresponds to the menu. This variable is then passed to a function where the active tab object can be retrieved.

<p-tabMenu #tab [model]="items" (click)="activateMenu(tab)"></p-tabMenu>

Answer №3

An old question that still needs addressing. One effective solution is to utilize templating. Start by defining the items:

this.items = [
  {label: 'Homework', icon: 'fa-file-pdf-o'},
  {label: 'Movies', icon: 'fa-file-pdf-o'},
  {label: 'Games', icon: 'fa-file-pdf-o'},
  {label: 'Pictures', icon: 'fa-file-pdf-o'}
];

Next, in your HTML:

<ng-template pTemplate="item" let-item let-i="index">
  <div (click)="onTabItemClick(i)">
    <span>
      <i class="{{ item.icon }}"></i>
    </span>
    {{ item.label }}
  </div>
</ng-template>

Finally, I have implemented a simple method:

onTabItemClick(i: number) {
  console.log(this.items[i])
}

By clicking, we can access the item based on its index.

Answer №4

just send it over as an argument to the function

(click)="retrieveCurrentItem(currentItem)"

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

Exploring the Differences between Angular's Http Module and the Fetch API

While I grasp the process Angular uses for HTTP requests, I find myself leaning towards utilizing the Fetch API instead. It eliminates the need to subscribe and unsubscribe just for a single request, making it more straightforward. When I integrated it int ...

Can optional properties or defaults have a specific type requirement defined for them?

When defining a type for a function's input, I want to designate certain properties as required and others as optional: type Input = { // Required: url: string, method: string, // Optional: timeoutMS?: number, maxRedirects?: number, } In ...

Having trouble with Angular CLI on your Windows 10 system?

Recently, I reinstalled node.js, npm, and angular-cli on my Windows 10 PC. However, after installing angular-cli using the command npm install -g @angular/cli, I encountered an issue. Despite having node.js version 8.1.2 and npm version 5.0.3, whenever I t ...

Issue with file upload controller in .net core 2.2 and Angular 7: IFormFile always returns null

Despite thorough research and checking other answers, my controller is not receiving any data. Correct API URIs are used and the request does reach the appropriate controller. Unique Angular Snippet: In the component.html file - input field setup <d ...

Angular Material - Adding tooltips to Mat-table rows

I am currently working with Angular Material Mat-Table and I have a requirement to show a tooltip when hovering over any row. Essentially, I need to filter data from mGridDataSource based on the row id. Since I am new to Angular, I would greatly appreciate ...

Utilizing emotion with MUI v5 for dynamic theming

After upgrading MUI from v4 to v5, I'm facing some difficulties grasping the concept of theming with the various solutions available. I find it challenging to determine when to use MUI theming/styling components and when to opt for emotion ones. Whil ...

Can we specify a more specific type for an argument in Typescript based on another argument in a function?

I'm in the process of developing a compact DSL for filter operations and crafting helper methods to support it. Suppose I have a function const equals = (left, right) => {} This function needs to be typed so that the left value is a field within ...

Storing images in Azure Blob Storage

I am currently using Angular 2 on the frontend and Node.js for the backend. I am facing an issue while attempting to upload a file to Azure storage blob container. Whenever I try to send the image to the API, an error occurs. Any assistance in this matter ...

Ways to adjust the ngx-pagination color scheme?

I am looking to customize the background color of ngx-pagination Here is my current code: <pagination-controls class="custom-pagination" id="indicadorPaginationResults" (pageChange)="p=$event" maxSize="9" directionLinks="true" autoHide="true" previ ...

Receiving multiple Firebase notifications on the web when the same application is open in multiple tabs

I have implemented firebase push notifications in Angular 7 using @angular/fire. However, I am facing an issue where I receive the same notification multiple times when my application is open in multiple tabs. receiveMessage() { this.angularFireMess ...

When the value of a Formcontrol is changed using valueAccessor.writeValue(), it remains unchanged

Encountering a similar issue as seen in this stack overflow post, but the solution provided isn't resolving the issue. Perhaps you can offer assistance on that thread. In my scenario, I have created a directive for formatting phone numbers: import { ...

Tips for implementing multiple yield generators in redux-saga

Our redux-saga generator has multiple yield statements that return different results. I am struggling with typing them correctly. Here's an illustration: const addBusiness = function* addBusiness(action: AddBusinessActionReturnType): Generator< ...

`Firebase User Instance and Custom Firestore Document`

Recently, I posted a question regarding Google Firebase Angular Firestore switchMap and encountered some issues. The question can be found here. After exploring AngularFireAuth, I learned that it is used to create a User object with fixed values, requirin ...

ReactNative: When attempting to navigate, a TypeError occurred - this.props.navigation.navigate is not a function

It's confusing to see how this issue is occurring, even though all props have been properly typed. The goal is to pass the navigator to the bottom bar component in order to navigate onPress. Initially, I define the props interface: export interface B ...

Having trouble accessing a downloaded image saved in local files from Amazon S3 using the AWS SDK in Node.js

I am currently using the node.js aws-sdk package to download files from s3 storage. However, when I download a jpeg image and save it as a local file, I am unable to view it. Is this the correct method for downloading jpeg images? public async downloadFi ...

NestJS Ensures Type Safety for Mongoose Models, but Model Functions Expecting Incorrect Types (Any)

Shema Interfaces export interface MyCat { name: string; color: string; } export type Cat = MyCat & Document; export const CatSchema = new Schema({ name: { type: String, required: true, }, color: { type: String, required: tr ...

Error: The "res.json" method is not defined in CustomerComponent

FetchData(){ this.http.get("http://localhost:3000/Customers") .subscribe(data=>this.OnSuccess(data),data=>this.OnError(data)); } OnError(data:any){ console.debug(data.json()); } OnSuccess(data:any){ this.FetchData(); } SuccessGe ...

Defining TypeScript class events by extending EventEmitter

I have a class that extends EventEmitter and is capable of emitting the event hello. How can I properly declare the on method with a specific event name and listener signature? class MyClass extends events.EventEmitter { emitHello(name: string): void ...

What is the best approach to handle Flow types for component props and getDerivedStateFromProps when the props are not the same

Having a Component with its props, an additional prop is added for getDerivedStateFromProps. The issue arises when setting the props with the additional one, throwing an error that the prop is not being used. Conversely, setting it without the extra prop c ...

Bidirectional binding in *ngFor with an Array of non-object elements

I have a straightforward array called tags = [];, and I am inserting a blank element into it when using the addNew() method like this: this.tags.push("");. This action creates an empty element inside the array. Currently, I am utilizing this array to dyna ...