Achieving conditional styling in Angular is possible by using attribute directives. To add a certain class to a div based on a boolean value, you can utilize the syntax:
div [class.some_class]="isActive"
.
If you need to display content based on a specific condition, consider employing the *ngIf
structural directive (or ngSwitch
). For example:
<div> <h1 *ngIf="isActive">I'm Active</h1> </div>
For more information, refer to: https://angular.io/guide/attribute-directives
In addition, if you have a list of classes with corresponding boolean values in your controller, you can do the following:
In your TypeScript file:
this.currentClasses = {
'saveable': this.canSave,
'modified': !this.isUnchanged,
'special': this.isSpecial
};
In your template file, apply ngClass
:
<div [ngClass]="currentClasses">This div is initially saveable, unchanged, and special</div>
Source code from: https://angular.io/guide/template-syntax#ngclass