2

I'm using an ionic ion-icon

<ion-icon name="checkmark" [class]="condition ? 'class1' : ''"></ion-icon>

I'd like to add an extra class if the condition is true, but dont add the extra class if the condition is false.

Problem is, if the condition is false it removes all the pre-defined classes on the icon from Ionic Framework.

1
  • 1
    Before spamming solutions.... Are you using AngularJs or Angular? You entered both tags but the frameworks are completely different. Commented Sep 1, 2017 at 9:41

2 Answers 2

10

Try to avoid binding to class directly.

Use either

[class.class1]="condition"

or

[ngClass]="condition ? 'class1' : ''"

With binding to class you explicitly bind the whole property value, instead of a single class.

Sign up to request clarification or add additional context in comments.

Comments

1

Maybe It's an "oldie", but this is how I solved my problem in case someone's looking an example of how to append classes conditionally to existing ones.

Basically I wanted to keep the fa bootstrap class applied, and only change the chevron from right to left if the side bar is collapsed or not. Also worked with a string literal and a terenary but get's messy, this way is much better (I think).

<button (click)="showHideSideClicked()">
    <span class="fa" [ngClass]="{'fa-chevron-left': isSideNavVisible, 'fa-chevron-right': !isSideNavVisible}"></span>
</button>

More about it @ NgClass

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.