如何在Angular Material2中获取活动选项卡 [英] How to get the active tab In Angular Material2

查看:66
本文介绍了如何在Angular Material2中获取活动选项卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取哪个标签处于活动状态.我尝试使用@ViewChild装饰器并以这种方式访问​​元素属性,但它返回null.

I want to get which tab is active. I tried to use a @ViewChild decorator and accessing the element properties that way, but it returns null.

组件:

import {Component, OnInit, ViewChild} from '@angular/core';

@Component({
  selector: 'material-app',
  template: `
  <md-tab-group #tabGroup>
      <md-tab label="Tab 1">Content 1</md-tab>
      <md-tab label="Tab 2">Content 2</md-tab>
  </md-tab-group>
  `
})
export class AppComponent implements OnInit {

  @ViewChild('tabGroup') tabGroup;

  constructor() {
  }

  ngOnInit() {
    console.log(this.tabGroup); // MdTabGroup Object
    console.log(this.tabGroup.selectedIndex); // null
  }

}

柱塞预览

推荐答案

好吧,我不确定我是否理解您的问题,因为默认情况下,索引总是从零开始计数除非手动设置 [selectedIndex] property.

Well, I'm not sure if I understood well your question because, by default the index always starts counting from zero unless you set manually the [selectedIndex] property.

无论如何,如果您确实想查看在初始化上选择了哪个选项卡,则可以实现AfterViewInit界面并执行以下操作:

Anyway, if you really want to see which tab is selected on initialization you could implement the AfterViewInit interface and do the following:

export class AppComponent implements AfterViewInit, OnInit {

...

  ngAfterViewInit() {
    console.log('afterViewInit => ', this.tabGroup.selectedIndex);
  }
}

另一方面,如果您要检查根据更改选择的选项卡(更有意义),请执行以下操作:

On other hand, if you want to check which tab is selected based on changes (what makes more sense), here you go:

HTML:

<mat-tab-group #tabGroup (selectedTabChange)="tabChanged($event)">
  <mat-tab label="Tab 1">Content 1</mat-tab>
  <mat-tab label="Tab 2">Content 2</mat-tab>
</mat-tab-group>

组件:

tabChanged(tabChangeEvent: MatTabChangeEvent): void {
  console.log('tabChangeEvent => ', tabChangeEvent);
  console.log('index => ', tabChangeEvent.index);
}

演示

这篇关于如何在Angular Material2中获取活动选项卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆