typescript - 無法在 Angular 15 的標籤頁標題/標籤中點擊按鈕
我目前正在嘗試使用 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;
}
答案#1
找到問題了,Material 15 已經加入了 pointer-events 規則並設置為 None,覆蓋這個應該可以讓點擊事件調用 ts 方法
<mat-tab-group animationDuration="0ms" class="allow-tab-events">
</mat-tab-group>
.allow-tab-events ::ng-deep .mdc-tab .mdc-tab__content{
pointer-events: all;
}
答案#2
在這裡補充一些更具體的內容,Material Design 規範並沒有提到可以關閉分頁的功能。
然而,有提到如果一個元素設定了 point-events: none,但其子元素之一設定了 pointer-events:auto,則:
指標事件將在事件捕獲/冒泡階段適當地在其向/從子孫元素傳遞的過程中觸發此父元素上的事件監聽器
你可以在這裡閱讀更多相關資訊。
所以,與其對所有標籤一律套用 pointer-events:all,你可以簡單地將它加到圖示的樣式中:
<mat-icon style="pointer-events: auto;" *ngIf="index > 1" (click)="removeTab(index)">{{tab.icon}}</mat-icon>
或者我猜你也可以建立一個可點擊圖示的類別:
.clickable-icon {
pointer-events: auto;
}
目前在 angular/components 倉庫中有兩個開放的問題,分別在這裡和這裡,你可以關注它們的解決進度。
