Angular mat-tab 从另一个类返回到第一个选项卡

问题描述

我使用 mat-tab-group 创建两个选项卡,然后链接到其他组件:

            <mat-tab-group>
                <mat-tab label="Notifications">
                    <app-notification-rules-container>
                    </app-notification-rules-container>
                </mat-tab>
                <mat-tab label="Create New">
                     <app-notification-account>
                     </app-notification-account>
                </mat-tab>
            </mat-tab-group>

app-notification-account 组件上,我有一个取消按钮,单击该按钮后,我想返回到第一个选项卡。如何从不同的组件类导航回第一个选项卡?

enter image description here

解决方法

在您的子组件中使用@Output。当您想将数据从子组件传输到父组件时,它会有所帮助。 所以让我们在 app-notification 中说你正在处理一个交叉按钮,所以当这个按钮被点击时,发出一个事件,该事件将由父级(其中 mat-tab-group)监听,并在 mat-tab-组,您可以使用 selectedIndex 属性来更改选定的选项卡。

https://angular.io/guide/inputs-outputs

所以 in-app-notification-account.ts

...
 constructor() {
   @Output() changeTab = new EventEmitter<();
   // this will emit event,which will be listened by parent
   handleCancel(){
    this.changeTab.emit(true)
  }
}

在使用 mat 选项卡的父组件中 在 .html 中

<mat-tab-group [selectedIndex]="selectedIndex">
<mat-tab label="Notifications">
                    <app-notification-account (changeTab)="changeTab()">
                    </app-notification-account>
                </mat-tab>
    </mat-tab-group>

in .component.ts 
.. changeTab() {
   this.selectedIndex = this.selectedIndex === 1 ?0:1
  // or if you always want to go to first tab just set selectedIndex = 0
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...