首页 > 解决方案 > Angular2 how to change a css calls using ng class but only for specific elements

问题描述

I have a mat-accordion and when a user clicks mat-expansion-panel I want to change out the icon CSS class so far I have that working but I need it to change the class for only the selected panel here is my code

html

<mat-expansion-panel hideToggle (opened)="onExpand()" (closed)="onCollapse()">
  <mat-expansion-panel-header>
    <mat-panel-title>
      <mat-icon [ngClass]="calculateClasses()" id="panel1">lock</mat-icon>
      <div>
        <div class="header-text">Change password</div>
        <div class="header-text-sub">*********</div>
      </div>
    </mat-panel-title>
  </mat-expansion-panel-header>
  <app-change-password></app-change-password>
</mat-expansion-panel>

ts

onExpand() {
  this.panelOpenState = true
}

onCollapse() {
  this.panelOpenState = false
}

calculateClasses() {
  let element = document.getElementById('panel1');
  //document.getElementById('panel1')
  if (this.panelOpenState == true) {
    return "circle-icon-selected"
  } else {
    return "circle-icon"
  }
}

Trying to change the code for mat-icon [ngClass]="calculateClasses()"

Updated code, as you can see there are two panels and I only want to change the icon in the panel that is currently opened

<mat-expansion-panel hideToggle (opened)="onExpand()" (closed)="onCollapse()">
  <mat-expansion-panel-header>
    <mat-panel-title>
      <mat-icon [ngClass]="panelOpenState ? 'circle-icon-selected' : 'circle-icon'">lock</mat-icon>
      <div>
        <div class="header-text">Change password</div>
        <div class="header-text-sub">*********</div>
      </div>
    </mat-panel-title>
  </mat-expansion-panel-header>
  <app-change-password></app-change-password>
</mat-expansion-panel>

<mat-expansion-panel hideToggle (opened)="onExpand()" (closed)="onCollapse()">
  <mat-expansion-panel-header>
    <mat-panel-title>
      <mat-icon [ngClass]="panelOpenState ? 'circle-icon-selected' : 'circle-icon'">phone_outline</mat-icon>
      <div>
        <div class="header-text">Change support PIN</div>
        <div class="header-text-sub">3402</div>
      </div>
    </mat-panel-title>
  </mat-expansion-panel-header>
  <app-support-pin></app-support-pin>
</mat-expansion-panel>

标签: angularangular-material

解决方案


阅读这一篇 或这一篇

[ngClass]="panelOpenState ? 'circle-icon-selected' : 'circle-icon'"

onExpand(num:number) {
    if(num==1) {
        this.panel1OpenState = true;
    } else if(num==2) {
        this.panel2OpenState = true;
    }
}

onCollapse(num:number) {
    if(num==1) {
        this.panel1OpenState = false;
    } else if(num==2) {
        this.panel2OpenState = false;
    }
}

现在通过更改数字调用第一个面板中的 onExpand(1) 和 onCollapse(1) 等函数。


推荐阅读