【发布时间】:2020-05-05 02:29:51
【问题描述】:
我正在尝试动态地为 mat-panel 提供一个类,但我无法正确地做到这一点。下面是我的代码
.ts
@Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.scss']
})
export class MenuComponent implements OnInit {
activeIndex = 0
constructor(private cd : ChangeDetectorRef) { }
menuList = [
{label: 'Menu 1' ,name: 'menu-1', childs: ['item1','item2','item3']},
{label: 'Menu 2' ,name: 'menu-2', childs: ['item1','item2']},
{label: 'Menu 3' ,name: 'menu-3', childs: ['item1','item2','item3']},
]
setIndex(index: number) {
this.activeIndex = index
this.cd.detectChanges() // not working
}
}
.html
<div class="nav">
<mat-accordion>
<mat-expansion-panel *ngFor="let menu of menuList; let i = index" (click)="setIndex(i)">
<mat-expansion-panel-header [ngClass]="{'active': activeIndex === i}">
<mat-panel-title>
{{menu.label}}
</mat-panel-title>
</mat-expansion-panel-header>
<ul>
<li *ngFor="let submenu of menu.childs">
{{submenu}}
</li>
</ul>
</mat-expansion-panel>
</mat-accordion>
</div>
.scss
.active{
color: red;
background-color: rgba(100,100,100,1);
}
我还使用 changeDetector 来检测更改,但活动 css 仍然不适用。通过检查,我可以检查由 css 添加的类未正确应用。颜色已更改,但未应用背景颜色
演示链接 https://stackblitz.com/edit/angular-a8pqfu?embed=1&file=src/app/menu/menu.component.css
【问题讨论】:
-
您申请的是
mat-expansion-panel-header,您应该申请的是background-color到mat-expansion-panel。如果我误解了您的要求,请纠正我 -
@Aravind 感谢您的回答,但如果我将它应用于 mat-expansion-panel ,我只想将它应用于标题,而不是它也适用于内容。我不想要,唯一的问题是背景颜色,字体颜色正确应用
-
请看答案,如果这不能解决您的问题,请告诉我
标签: angular