Angular2如何使用ng类更改CSS调用,但仅适用于特定元素

时间:2018-07-24 06:25:49

标签: angular angular-material

我有一个手风琴手风琴,当用户单击mat-expansion-panel时,我想更改图标CSS类,到目前为止,我已经可以使用了,但是我需要它来仅更改所选面板的类,这是我的手风琴代码

<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>

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"
    }

尝试更改mat-icon [ngClass]="calculateClasses()"的代码

更新后的代码,如您所见,有两个面板,我只想更改当前打开的面板中的图标

<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>

1 个答案:

答案 0 :(得分:0)

阅读此one或此one

[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)之类的函数,依此类推,方法是更改​​数字。