如何根据属性将类应用到活动的“角度材质”选项卡?

问题描述 投票:0回答:1

我有一个名为 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');
      });
    }
  }
angular angular-material
1个回答
0
投票

你可以使用 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>

https://angular.io/api/common/NgClass

© www.soinside.com 2019 - 2024. All rights reserved.