Angular MatTabChangeEvent不会在页面加载时触发

时间:2020-05-12 20:51:30

标签: angular angular-material mat-tab

我正在使用(selectedChange)="functionName($event)"获取活动标签的索引。但是,在页面加载时,我无法触发此事件,因为它仅在我更改选项卡至少一次以获得包含两个对象MatTabChangeEventtab的返回的index对象后才触发。

在两个标签中,我都有一个带有分页的垫子桌子。另外还有一个搜索栏,可以从数据库搜索数据并将其显示在各自的选项卡中,但是对我来说,问题是,如果页面加载用户直接搜索了搜索栏,那么我将不知道哪个选项卡当前处于活动状态,因此我的条件语句显示根据用户搜索在其各自选项卡中的数据将给出Uncaught error处的this.activeTab.index不存在。但是,一旦用户实际更改了选项卡,那么我就拥有了活动的选项卡索引值,并且我的代码可以正常工作。

那我如何也可以在页面加载时获取MatTabChangeObject?

注意:我不能将MatGroupViewChild一起使用,因为它不会像对象一样返回MatTabChangeEvent

这是我的代码

 if(this.tabEvent.index === 0) {
      $event.map((a: string) => {
        this._printService.getParcelById(this.vId, a, true).subscribe(res => {
          data.push(res);
          this.child.dataLength = $event.length;
        }, err => {
          data = [];
          this._sb.open({
            message : 'Either the parcel id does not exist in the system or it is incorrect',
            type: 'error'
          })
        });
      });
      this.dataSource$ = of(data);
    }
    else if(this.tabEvent.index === 1) {
      $event.map((a: string) => {
        this._printService.getParcelById(this.vId, a, false).subscribe(res => {
          data.push(res);
          this.child.dataLength = $event.length;
        }, err => {
          data = [];
          this._sb.open({
            message : 'Either the parcel id does not exist in the system or it is incorrect',
            type: 'error'
          })
        });
      });
      this.dataSource$ = of(data);
    }

我在函数中发出eventChange值,然后将该值分配给类型为this.tabEvent的{​​{1}}变量

1 个答案:

答案 0 :(得分:1)

这就是我在项目中实现Mat Tab的方式

在HTML中:

(selectedChange)="selectedTabChange($event)"

TS:

index = 0;

ngOnInit(): void {
  ...
  this.onTabChanged();
}

selectedTabChange(event) {
  this.index = this.event.index
  this.onTabChanged()
}

onTabChanged() {
  if (this.index==0) {
    ...
  } else if (this.index==1) {
    ...
  }
  ...
}

我什至在某些页面中都有按路线导航的标签...

那里,我在TS上有细微的变化

constructor(ar: ActivatedRoute) { }

ngOnInit(): void {
  this.ar.queryParams.subscribe(param => {
    if (param.tab) this.index = Number(param.tab); else this.index = 0;
    this.onTabChange()
  })
  ...
}

希望有帮助!

相关问题