1
votes

I am trying to give a class dynamically to mat-panel but i am not able to do it correctly. Below is my code

.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);
  }

I have also used changeDetector for detecting changes but active css still not applies. By inspecting i can check class is added by css is not applied correctly. Color is changed but background color is not applied

Demo link https://stackblitz.com/edit/angular-a8pqfu?embed=1&file=src/app/menu/menu.component.css

1
you're applying to the mat-expansion-panel-header you should be applying background-color to mat-expansion-panel. Correct me if I'm misunderstood your requirementAravind
@Aravind Thanks for answer but i want to apply it to only header if i apply it to mat-expansion-panel than it will also applies to content. Which i don't want and thing is only issue is with background color , font color applies correctlyMamta
please have a look at the answer, let me know if that doesn't solves your issueAravind

1 Answers

1
votes

Actually the background-color is applied but when you hover on it, the color is inherited, you should be overriding that by adding the below code in your scss file

 .mat-expansion-panel-header.mat-expanded:focus, 
 .mat-expansion-panel-header.mat-expanded:hover{
    background-color: rgba(100,100,100,1);
  }