【问题标题】:Angular mat-tab go back to first tab from another classAngular mat-tab 从另一个类返回到第一个选项卡
【发布时间】:2023-04-02 23:20:02
【问题描述】:

我正在使用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 组件上,我有一个取消按钮,当单击该按钮时,我想返回到第一个选项卡。如何从不同的组件类导航回第一个选项卡?

【问题讨论】:

    标签: angular angular-material mat-tab


    【解决方案1】:

    在您的子组件中使用@Output。当您想将数据从子组件传输到父组件时,它会有所帮助。 所以让我们在应用通知中说你正在处理一个十字按钮,所以当点击这个按钮时,发出一个事件,该事件将被使用的父级(其中 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
    }
    

    【讨论】:

    • 标签仍然变回第一个。我可以看到changeTab() 在我单击取消按钮时被调用,但它不会返回到第一个选项卡。我尝试将this.selectedIndex = 0; 放入changeTab() 函数中,但它不起作用
    • 您是否在主组件中使用 0 启动了 selctedIndex 并在 mat-tab-group 中添加了 selectedIndex?
    • selectedIndex = 0 ,将使第一个选项卡成为活动选项卡,您必须在取消按钮所在的组件中使用输出
    • 是的,我已将 selctedIndex 添加到主要组件和 mat-tab-group
    • 在你想要取消按钮功能的组件中使用@output
    猜你喜欢
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    相关资源
    最近更新 更多