【发布时间】:2022-12-11 14:54:30
【问题描述】:
我目前正在尝试使用 Angular Material 实现选项卡功能。我一辈子都无法点击标题中的按钮。我试过在选项卡周围移动点击事件,但它似乎没有在任何地方触发。
我正在尝试添加可以通过单击关闭图标关闭选项卡的功能。我试过把它放在一个 div 中。我试过使用 div 而不是按钮。
这是用户界面:
<mat-tab-group animationDuration="0ms">
<div *ngIf="tabs">
<mat-tab *ngFor="let tab of tabs; let index = index" [ngSwitch]="tab.type">
<ng-template mat-tab-label>
<div style="display: flex; flex-direction: row; align-items: center;">
{{tab["title"]}}
<div>
<button style="color:black" mat-icon-button (click)="closeTab($event, index)">
<mat-icon>close</mat-icon>
</button>
</div>
</div>
</ng-template>
<div *ngSwitchCase="'Work'">
<p>Work</p>
</div>
<div *ngSwitchCase="'Case'">
<p>Case</p>
</div>
<div *ngSwitchCase="'Document'">
<app-base></app-base>
</div>
</mat-tab>
</div>
</mat-tab-group>
</div>
和后端:
import {MatTab, MatTabGroup} from '@angular/material/tabs';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent {
@ViewChild(MatTabGroup, {read: MatTabGroup})
public tabGroup: MatTabGroup;
@ViewChildren(MatTab, {read: MatTab})
public tabNodes: QueryList<MatTab>;
tabs: Tab[] = [];
workCounter: number = 0;
caseCounter: number = 0;
documentCounter: number = 0;
closedTabs: number[] = [];
ngOnInit(): void {
}
addNewTab(type: string): void {
let tab = new Tab();
switch (type) {
case 'Work':
this.workCounter++;
tab.type = type;
tab.title = `${type} # ${this.workCounter}`
break;
case 'Document':
this.documentCounter++;
tab.type = type;
tab.title = `${type} # ${this.documentCounter}`
break;
case 'Case':
this.caseCounter++;
tab.type = type;
tab.title = `${type} # ${this.caseCounter}`
break;
}
this.tabs.push(tab);
}
closeTab(event: Event, index: number) {
console.log(index);
event.stopPropagation();
this.closedTabs.push(index);
this.tabGroup.selectedIndex = this.tabNodes.length - 1;
console.log(index);
}
}
class Tab {
type: string;
title: string;
index: number;
}
【问题讨论】:
-
我无法重现问题,代码似乎没问题,你能在 stackblitz 中重现吗?
-
从 Angular 15 降级到 12 为我解决了这个问题。我不想将其添加为答案,因为它在 15 上不起作用应该有实际原因。
标签: angular typescript angular-material