What is the best way to change between different Angular 2 material tabs using typescript?

I need help with switching tabs using buttons

<md-tab-group>
<md-tab label="Tab 1">Content 1</md-tab>
  <md-tab label="Tab 2">Content 2</md-tab>
</md-tab-group>
<button md-button (click)="showTab1()">Show Tab 1</button>
 <button md-button (click)="showTab2()">Show Tab 2</button>

Is it possible for the showTab1() function to switch to tab 1 if already on Tab 1, and for showTab2() to execute when its respective button is clicked?

Answer №1

If you want to utilize the [selectedIndex] @Input feature for managing tabs within a mat-tab-group, here's how you can do it:

In your Component:

selectedIndex = 0;

selectTab(index: number): void {
  this.selectedIndex = index;
}

In your Template:

<mat-tab-group [selectedIndex]="selectedIndex">
  <mat-tab label="Tab 1">Content 1</mat-tab>
  <mat-tab label="Tab 2">Content 2</mat-tab>
</mat-tab-group>

<button mat-button (click)="selectTab(0)">Show Tab 1</button>
<button mat-button (click)="selectTab(1)">Show Tab 2</button>

Check out the STACKBLITZ DEMO

Alternatively, you can also create a reference to the mat-tab-group and manipulate it directly in the template like this:

<mat-tab-group #tabGroup>
  <mat-tab label="Tab 1">Content 1</mat-tab>
  <mat-tab label="Tab 2">Content 2</mat-tab>
</mat-tab-group>

<button mat-button (click)="tabGroup.selectedIndex = 0">Show Tab 1</button>
<button mat-button (click)="tabGroup.selectedIndex = 1">Show Tab 2</button>

Try out the STACKBLITZ DEMO

Answer №2

To implement this functionality, start by declaring a variable like selectedTab: number = 1. Then, construct your template as follows:

<md-tab-group>
<md-tab *ngIf="selectedTab == 1" label="Tab 1">Content 1</md-tab>
  <md-tab *ngIf="selectedTab == 2" label="Tab 2">Content 2</md-tab>
</md-tab-group>
<button md-button (click)="selectedTab = 1">Show Tab 1</button>
 <button md-button (click)="selectedTab = 2">Show Tab 2</button>

Answer №3

Inside TypeScript

  @ViewChild('tabGroup') tabGroup;

  ngAfterViewInit(): void {
    let selectedTabIndex = this.selectedIndex;
    this.selected_tab_label = this.tabGroup._allTabs._results[selectedTabIndex].textLabel;
  }

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

get a duplicate of an object

Is this the proper method for creating a duplicate of an object? class ObjectWrapper { private _obj; /*** * Copy object passed as argument to this._obj */ constructor (_obj: Object) { this._obj = _obj; } /** Return copy of this._ ...

Error: Invalid connection string for ELF Lambda detected

Having an issue with a lambda function that connects to a remote MongoDB on an EC2 instance using TypeScript. While I can connect to the database locally, there is an ELF error when running in lambda. It seems to be related to mismatched binaries of npm pa ...

Angular API snapshot error: The type 'IJobs' does not match the expected type 'IJobs[]'

Currently, I am in the process of learning and attempting to construct a job board using Angular 10. Although my API setup seems to be functioning properly, when navigating to the job detail page on Chrome, an error is displayed: ERROR in src/app/job-det ...

React's .map is not compatible with arrays of objects

I want to retrieve all products from my API. Here is the code snippet for fetching products from the API. The following code snippet is functioning properly: const heh = () => { products.map((p) => console.log(p.id)) } The issue ari ...

Searching through an array of objects with ng2-completer does not yield any search results

Having some trouble with the ng2-completer plugin when trying to enable auto-complete functionality in a search box. The issue arises when attempting to use an array of objects instead of just strings, resulting in a 'No Results found' message. E ...

Place a hook following the storage of a variable in the device's memory

Within a component, I am facing the following situation: const [home, setHome]=useState(false) if(home){ return(<Redirect push={true} to="/" />); } setItem("isRegistered", resquest[0].user) setHome(true) The issue here is that ...

Prevent Typescript from flagging unnecessary warnings about unassigned values that will never be assigned

One of my functions serves as a shortcut for selecting values from synchronous observable streams. The function in its entirety looks like this: export function select<T>(inStream: Observable<T>): T { let value: T; race( inStream, ...

Utilizing Angular 5 alongside the powerful ngx-cookie library and configuring it all within the system

Currently in the process of upgrading a project from AngularJS 1 to Angular 5. In need of a package for cookie manipulation, I came across ngx-cookie. However, facing a hurdle as I cannot alter systemjs.config.js as per the instructions provided, given t ...

Is it possible in Angular to generate a module and component without including a CSS file in a single command?

Is it possible to generate a Module linked to a component without automatically creating a css file? For example, the default method I've been using involves: ng generate module name / ng generate component name This results in the typical componen ...

Retrieve the thousand separator for numbers using Angular in various languages

When using the English locale, numbers appear as follows: 111,111,222.00, with a comma as the thousand separator and a point as the decimal separator. In languages like German, the same number would be represented as 111.111.222,00, reversing the positions ...

What could be causing my vis.js network's node hover popups to not function properly?

I've encountered an issue where, despite adding the 'title' property to my node objects, the pop up window with the title content doesn't appear when I hover over a node. Here are the options I've chosen and how I've set up m ...

The Recoil Nexus encountered an error: the element type provided is not valid. It should be a string for built-in components or a class/function for composite components, but an object was

Encountered the following error message: Error - Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. at ReactDOMServerRenderer.render ... This issue arose when integra ...

What is the best way to fetch the id of the option that has been chosen from a bootstrap drop-down menu?

I recently created a basic drop-down list like this: https://i.sstatic.net/4Tlxx.png Here is the HTML code for it: <select class="form-control" id='0' (change)="retrieveValue($event.target)"> <option id='0'>{{ g ...

When examining two arrays for similarities

I am dealing with two arrays within my component arr1 = ["one", "two"] arr2 = ["one", "two"] Within my HTML, I am utilizing ngIf in the following manner *ngIf="!isEnabled && arr1 != arr2" The isEnabled condition functions as expected, however ...

transferring attributes from a higher component to a lower one (modal)

https://i.sstatic.net/tSXb5.png https://i.sstatic.net/H4xmj.png I am relatively new to React and I want to share a detailed problem description: I have a Todo project that consists of multiple interfaces. The main interface displays all the lists, each ...

Connect the child content to the form

Are there any methods to connect a projected template (ContentChild) to the form specified on the child, such as adding formControlName after it has been rendered? I am having difficulty in finding relevant information online, possibly due to using incorr ...

How can I reference MyClass.new as a method in Typescript?

Within my code, I have an array of objects and each object is structured like this: { id: 'string', name: 'string' } There's a class defined as follows: class User { constructor(obj: Record<string, string>) { Object.as ...

The TypeScript rule in the project-specific .eslintrc.js file is not being applied as expected

Currently, I am following a tutorial on Ionic/Vue 3 which can be found here. However, when I try to serve the project, I encounter the following error: https://i.stack.imgur.com/k4juO.png It appears that my project-level .eslintrc.js file is not being ap ...

When I declare a second service in the constructor, my modal service no longer opens as expected

Recently, I came across this login method in Angular: email: string = ""; password: string = ""; login() { const credentials = { email: this.email, password: this.password }; this.userService.login(credential ...

Ways to dynamically link a JSON response object to an entity?

In my ng2 implementation, I have a user.service.ts file that calls a REST service and returns JSON data. The code snippet below shows how the getUser function retrieves the user information: getUser(id: number): Promise<User> { return this.http. ...