如何从子组件切换材质选项卡

时间:2020-06-30 05:29:40

标签: angular angular-material

我想基于子组件中的按钮单击来切换选项卡。我该怎么办

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

如何基于子组件中的下一个单击按钮来切换选项卡?

1 个答案:

答案 0 :(得分:1)

一种方法是使用@Output模式,子组件发出的事件是使用Angular的事件绑定(就像您监听点击事件时一样)在父级模板中接收的,

在子组件中:

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

在孩子的模板中:

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

在父母的模板中:

<mat-tab label="Second">
    <app-tab-child (next)="next()"></app-tab-child>
</mat-tab>
相关问题