maudulus maudulus - 1 year ago 69
CSS Question

Ionic 2: Add Class to Item While Removing Class From Other Items

I have a div full of buttons that, when clicked, should add a class (

selected-date-item
) that changes the color of the button. Immediately before that, I want to remove that class (
selected-date-item
) from any button that previously held that class.

CSS

.selected-date-item {
background:#272829;
color:white;
}


HTML

<button class="date-time-select" *ngFor="let chooseDate of possibleDates" (tap)="selectPickupDate(chooseDate)">{{chooseDate}}</button>


JS

selectPickupDate(selectedDate) {
this.selectedDate = selectedDate;
}


enter image description here => enter image description here

Answer Source

Use [ngClass]-directive to set a CSS-class dynamically .

<button [ngClass]="{'selected-date-item': chooseDate == selectedDate, 'not-selected-item': chooseDate != selectedDate}" *ngFor="let chooseDate of possibleDates" (tap)="selectPickupDate(chooseDate)">{{chooseDate}}</button>

[ngClass] broken out:

[ngClass]="{'selected-date-item': chooseDate == selectedDate, 'not-selected-item': chooseDate != selectedDate}"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download