我正在使用Angular和MaterialTabs模块。
我在组件中有一个选项卡列表,可以使用mat-tabs和ngFor显示这些选项卡,还有一个带有加号按钮的禁用选项卡。单击加号按钮时,我想添加一个新选项卡并立即关注该选项卡。 (类似于浏览器标签的工作方式。)
外观如下:
我通过两种方式将属性绑定到mat-tab-group的selectedIndex属性,并从按钮单击事件处理程序内的组件中对其进行设置。
您可以看到选项卡组的属性及其绑定的属性在工作时是相等的。
但是,我遇到了一个问题,如果我重新加载页面并首先单击该按钮,则绑定的属性会以某种方式中断:
在任何选项卡上单击一次似乎都可以永久解决此问题。重新加载页面后,问题再次出现。
根据我的理解,以下属性绑定将确保值始终相等,并且如果其中一个更改另一个,则将遵循:
[(selectedIndex)]="selectedIndexBinding"
那么,selectedIndexBinding为0时,selectedIndex如何为1?
如何解决此问题?
实时示例:
https://stackblitz.com/edit/angular-82vgrj
代码:
src / app / app.component.html
<mat-tab-group [(selectedIndex)]="selectedIndexBinding" #tabGroup>
<mat-tab *ngFor="let tab of tabs">
<ng-template mat-tab-label>
{{ tab }}
</ng-template>
</mat-tab>
<mat-tab disabled>
<ng-template mat-tab-label>
<button mat-icon-button (click)="addTab()">
+
</button>
</ng-template>
</mat-tab>
</mat-tab-group>
selectedIndex: {{ tabGroup.selectedIndex }}<br />
selectedIndexBinding: {{ selectedIndexBinding }}
src / app / app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
public selectedIndexBinding = 0;
public tabs = [];
public addTab() {
this.tabs.push("Tab");
this.selectedIndexBinding = this.tabs.length - 1;
}
}
您的问题来自您设置新索引的方式,因为button
以任何方式都计为tab
。
您需要使用以下方法检索原始的mat-tab-group
:
@ViewChild('tabGroup', {static: false}) tab: MatTabGroup;
并直接设置您想要的索引:
this.tab.selectedIndex = this.tabs.length - 1;
您可能会注意到我将其全部放入setTimeout
。它用于Angular lifecycle hooks,setTimeout触发一个新的Angular周期。
Here's your working StackBlitz。
代码:
src / app / app.component.html
<mat-tab-group [(selectedIndex)]="selectedIndexBinding" #tabGroup>
<mat-tab *ngFor="let tab of tabs">
<ng-template mat-tab-label>
{{ tab }}
</ng-template>
</mat-tab>
<mat-tab disabled>
<ng-template mat-tab-label>
<button mat-icon-button (click)="addTab($event)">
+
</button>
</ng-template>
</mat-tab>
</mat-tab-group>
selectedIndex: {{ tabGroup.selectedIndex }}<br />
selectedIndexBinding: {{ selectedIndexBinding }}
src / app / app.component.ts
import { Component, ViewChild } from '@angular/core';
import { MatTabGroup } from '@angular/material';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
@ViewChild('tabGroup', {static: false}) tab: MatTabGroup;
public selectedIndexBinding = 0;
public tabs = [];
public addTab(e: Event) {
this.tabs.push("Tab");
e.preventDefault();
setTimeout(() => {
console.log(this.tabs, this.tab.selectedIndex);
this.tab.selectedIndex = this.tabs.length - 1;
});
}
}