我有一个名为 editMode 的属性。当 editMode 为 true 时,如何将此 CSS 类仅应用于活动选项卡?
.tab-active-edit-mode {
border-top: none !important;
border-bottom: 2px solid #0078d2 !important;
background-color: #dddddd !important;
}
这是 Chat GPT 给出的答案,但看起来很笨拙。有更好的 Angular 方式吗?
ngAfterViewInit() {
this.updateTabStyles();
}
updateTabStyles() {
if (this.editMode) {
// Directly manipulate the DOM to add CSS class to the active tab
const activeTab = (this.tabGroup._elementRef.nativeElement as HTMLElement).querySelector('.mat-mdc-tab-group .mat-mdc-tab-active');
if (activeTab) {
activeTab.classList.add('tab-active-edit-mode');
}
} else {
// Remove the class if not in edit mode
const tabElements = (this.tabGroup._elementRef.nativeElement as HTMLElement).querySelectorAll('.mat-mdc-tab-group .mat-mdc-tab');
tabElements.forEach(tab => {
tab.classList.remove('tab-active-edit-mode');
});
}
}
你可以使用 ngClass 吗?这允许您根据编辑属性值在模板中添加类
<mat-tab-group>
<mat-tab label="First" [ngClass]="{ 'editing': editing, 'not-editing': !editing }"> Content 1 </mat-tab>
<mat-tab label="Second"> Content 2 </mat-tab>
<mat-tab label="Third"> Content 3 </mat-tab>
</mat-tab-group>