Search code examples
angularangular-directive

using ngClass directive is throwing exception?


I am having a small code snippet in my angular component HTML file. it uses ngClass directive. Unfortunately it's not working. I am using angular 5 in my project.

in my component stylesheet (progress-panel.component.scss)

chart-title,
.chart-title-value {
  font-size: 18px;
}

in the HTML file, (progress-panel.component.html) I am using the ngClass directive.

  <div *ngSwitchCase="'currency'" [ngClass]="{'chart-title-value' , 'text-right'}">
       {{ campaign.breakdown.total | pcCurrency }}
     <span class="text-muted">/ {{ campaign.budget | pcCurrency }}</span>
  </div>

however it is throwing some errors that i can see

compiler.js:485 Uncaught Error: Template parse errors:

appreciate it if you can help thank you


Solution

  • Your syntax is wrong:

    <div *ngSwitchCase="'currency'" [ngClass]="'chart-title-value text-right'">
         {{ campaign.breakdown.total | pcCurrency }}
         <span class="text-muted">/ {{ campaign.budget | pcCurrency }}</span>
    </div>
    

    will work.

    But it is very odd you are not just using the css class html sector instead aka

    <div class="chart-title-value text-right" *ngSwitchCase="'currency'">
         {{ campaign.breakdown.total | pcCurrency }}
         <span class="text-muted">/ {{ campaign.budget | pcCurrency }}</span>
    </div>
    

    I tend to only use the ngClass when i want to set stuff depending on component values aka

    <some-element [ngClass]="{'first': componentVariableBoolean, 'second': componentVariableBoolean}">...</some-element>