wuno wuno - 10 months ago 116
TypeScript Question

Angular 2 Change Class On Condition

I have three buttons in a view and on page load I am displaying the first buttons content. Once a button is clicked the button becomes active but on page load the initial button is not set to active. In order to show the first button active I added this to the div


The problem with this is now when another button is clicked the first button keeps the active class. I am evaluating the data being show based on a string. On click of each button the string changes.

How can I add a condition to check for the current string? So if the string matches the current data being show then add the active class to this button?

So something like this is what I am looking for,

[ngClass]="'active'" if "myString == ThisIsActiveString;

This is my current button, but the class is not added when I add it in this syntax

<button [class.active]="shown == EQUIFAX" (click)="shown = 'EQUIFAX'" type="button" id="equifax" class="btn btn-secondary">Equifax Report </button>

To be clear the string is defaulted to EQUIFAX on page load.

This is based on answer,

<button [ngClass]="'active' : shown == 'EQUIFAX'" (click)="shown = 'EQUIFAX'" type="button" id="equifax" class="btn btn-secondary">Equifax Report </button>

Answer Source

You can add css class based on condition in NgClass directive itself:

[ngClass]="{ 'active': myString == ThisIsActiveString }";

You can read more about NgClass directive and find examples here.