IamGrooot
IamGrooot

Reputation: 1040

How to switch material tab from child component

I want to switch the tabs based on button click in child component. How can I do that

parent component

<mat-tab-group #mytab>
    <mat-tab label="First">
        Content 1
        <br>
        <br>
        <br>
        <button (click)="next()">Next</button>

    </mat-tab>
    <mat-tab label="Second">
        <app-tab-child></app-tab-child>
    </mat-tab>
    <mat-tab label="Third"> Content 3 </mat-tab>
</mat-tab-group>

export class TabGroupBasicExample {
  @ViewChild("mytab", { static: true }) tab: any;

  next() {
    this.tab.selectedIndex = 1;
  }
}

Child Component

<p>
    tab-child !
</p>

<br>
<br>
<br>
<button (click)="next()">Next</button>

Stackblitz demo

How can I switch the tabs based on next button click in child component?

Upvotes: 1

Views: 1953

Answers (1)

Rafi Henig
Rafi Henig

Reputation: 6424

One approach is using @Output pattern, events emitted by child components, are received in parent's template using Angular's event binding (just as you would when listening for click events) as following:

In child component:

@Output() next = new EventEmitter<void>();

In child's template:

<button (click)="next.emit()">Next</button>

In parent's template:

<mat-tab label="Second">
    <app-tab-child (next)="next()"></app-tab-child>
</mat-tab>

Upvotes: 1

Related Questions