Clicked but nothing happened - what's wrong with the function?

For my project, I have incorporated tabs from Angular Material. You can find more information about these tabs here.

Below is the code snippet I am using:

<mat-tab-group animationDuration="0ms" >
    <mat-tab></mat-tab>
    <mat-tab (click)="setData(upgrade.name)" [label]="upgrade.name" *ngFor="let upgrade of upgradeType; let i = index"> </mat-tab>
  </mat-tab-group>

The function in question is as follows:

setData(data){
    alert(data)
}

However, on clicking the tab, the setData function does not execute. Any insights on why this might be happening?

Answer №1

mat-tab does not support the click property, so you will need to utilize the mat-tab-group property (selectedTabChange) instead. This will be triggered whenever a tab is changed.

Give this a try:

mat-tab.component.html

<mat-tab-group (selectedTabChange)="setData($event)" animationDuration="0ms" >
    <mat-tab></mat-tab>
    <mat-tab [label]="upgrade.name" *ngFor="let upgrade of upgradeType; let i = index"> </mat-tab>
</mat-tab-group>

mat-tab.component.ts

setData(event: MatTabChangeEvent) {
    console.log("click", event.tab.textLabel); //console out will be click {{upgrade.name}}
}

Check out the live example on stackblitz:

https://stackblitz.com/edit/angular-wzc6m3-rpap1a?file=src/app/tab-group-align-example.html

I hope this information proves useful :)

Answer №2

One possible solution is to utilize the selectedIndexChange event. You can refer to the code snippet and stackblitz link below for more details:
HTML:

<mat-tab-group 
               (selectedIndexChange)="test($event)">
 <mat-tab *ngFor="let tab of upgradeType; let index = index" [label]="tab.name">
   <button mat-raised-button
            class="example-delete-tab-button"
            (click)="removeTab(index)">
      Delete Tab
    </button>
  </mat-tab>
</mat-tab-group>

TS:

export class AppComponent {
  upgradeType=[];
  constructor(){
    let temp=new UpgradeType();
    temp.name="A";
    temp.id=1;
    this.upgradeType.push(temp);
    let temp2=new UpgradeType();
    temp2.name="B";
    temp2.id=2;
    this.upgradeType.push(temp2);
  }
  test(index){
    console.log(index);
    console.log(this.upgradeType[index]);
  }
}
export class UpgradeType{
  name:string;
  id:number;
}

NOTE: You can access the demo code in stackblitz => Demo code example

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

What is the best way to combine an array of objects into a single object in typescript?

Looking for some help with converting an array of objects into a single object using TypeScript. Here's the structure of the array: myArray = [ {itemOneKey: 'itemOneValue', itemTwoKey: 'itemTwoValue'}, {itemThreeKey: ' ...

An Angular module downloaded from npm seems to be lacking the required @NgModule declaration

There seems to be a missing @NgModule and @Directive declarations in an NPM module, even though they exist in the source code on Github. This is causing an issue with importing a directive for databinding from an HTML attribute. I am attempting to utilize ...

Leveraging @Input in Angular 2 to transmit information to ng2-typewriter

Currently, I have integrated ng2-typewriter into my project and I would like it to function as a singleton for reusability. While most aspects are working smoothly, I am facing challenges with the plugin's predefined methods as I try to incorporate m ...

Discover the Location and Sign Up for Angular2+ Service

I'm currently using the Google Maps API to retrieve a user's geoLocation data, including latitude and longitude. My goal is to pass this information to a web API service in order to receive JSON output of surrounding addresses. I have implemented ...

How to assign attributes to all child elements in Angular?

I have a unique component in Angular that I utilize throughout my app. It's a button component which I use by calling <app-delete-btn></app-delete-btn> wherever needed. I tried to set the tabindex="1" attribute for my component ...

After pushing to history in React, the rendered component fails to display on the screen

I am in the process of developing a React application. Here are the dependencies I am currently using: "react": "^17.0.2", "react-dom": "^17.0.2", "react-helmet": "^6.1.0", "react-router" ...

Async await causing failure in change detection

1. Displaying a loading animation while waiting for API data to resolve 2. Once the API response is received, turning off the loader flag and attempting to access the div element within the flag 3. The flag value is updated but the DOM is not refreshed, le ...

What is the best way to incorporate a string value from an external file into a variable in TypeScript without compromising the integrity of special characters?

I am encountering an issue with importing a variable from a separate file .ts that contains special characters, such as accents used in languages like French and Spanish. The problem I am facing is that when I require the file, the special characters are ...

Webpack may suggest, "An extra loader might be needed" within a React.js project

I recently created a React project with two separate workspaces, named 'webmail' and 'component'. In the 'component' workspace, I added a small tsx file that I wanted to utilize in the 'webmail' workspace. Below is t ...

Tips for enlarging a mat-expansion-panel by pressing a button in Angular?

Currently, I have a component featuring expansion panels. When clicking on the "All" tab button, all mat-expansion-panels expand perfectly in the body below. However, my goal is to make it so that clicking on the B tab will only activate and expand the pan ...

The navigator.geolocation.watchPosition call did not return any available position information

I offer a service that monitors the position of devices: getLocation(opts): Observable<any> { return Observable.create(observer => { if (window.navigator && window.navigator.geolocation) { window.navigator.geolocat ...

A guide on setting up a countdown timer in Angular 4 for a daily recurring event with the help of Rxjs Observable and the Async Pipe

I'm currently working on developing a countdown timer for a daily recurring event using Angular 4, RxJS Observables, and the Async Pipe feature. Let's take a look at my component implementation: interface Time { hours: number; minutes: numbe ...

Screen a roster for shared elements with another roster

Within my dataset, I am working with a List of Objects that adhere to the following Model structure: export class Animal{ public aniId: number; public aniName: string; } export Class Zoo{ public id: number; public name:string; public aniId: number ...

Using the reduce method in JavaScript or TypeScript to manipulate arrays

Just exploring my culture. I have grasped the concept of the reduce principle var sumAll = function(...nums: number[]):void{ var sum = nums.reduce((a, b) => a + b , 0); document.write("sum: " + sum + "<br/>"); } sumAll(1,2,3,4,5); The r ...

Enforcement of Typescript Field Type Lax During Assignment

My current issue involves a constructor that is supposed to set the value of _device. The field is specifically designed to be of type number, and the constructor parameter is also expected to be of type number. However, when a parameter of type string is ...

I am having trouble figuring out the issue with the state and how to properly implement it in Typescript

I am having difficulties sending emails using Nodemailer, TypeScript, and NextJS. The contact.tsx file within the state component is causing errors when using setform. As a beginner in TypeScript, I have been unable to find a solution to this issue. Any he ...

Tips for updating the styles within a class for Angular 6 dynamically

Currently, I am able to update the button design using ng-container. Here is a snippet of the code: <ng-container *ngIf="isDisabled;"> <button class="bot-btn-disabled" (click)="confirm()" [disabled]=this. ...

Utilizing Vue 3/Nuxt 3 Scoped Slots to Automatically Deduce Generic Data Types from Props

I am looking to incorporate a carousel component into Nuxt v3. The component will be passed an array of items, focusing solely on the logic without handling styling or structuring. Currently, this is what my component looks like: components/tdx/carousel. ...

Issue with page reload in Angular 8 when URL contains a dot

When the URL contains a dot(.) and we attempt to reload the page using the browser's reload function, the following error occurs: The resource you are seeking has been deleted, its name has been changed, or it is currently unavailable. We prefer not ...

Leverage HighCharts on numerous occasions

Hello there, I'm curious about utilizing the Highcharts library in my Angular application. I have 3 tabs (sale / rental / rental & sale), each with 3 identical diagrams that display different data from my API. Currently, my setup only works on t ...