-1

I want to style a div based on a bool property "isActive" on my controller. Is this possible with angular?

<div class="col-md-3" (click)="isActive = !isActive">
    <div class="center">
        <i class="fa fa-calendar"></i><br>
        <span>Activate</span>
    </div>
</div>
AT82
  • 71,416
  • 24
  • 140
  • 167
netshark1000
  • 7,245
  • 9
  • 59
  • 116

2 Answers2

1

Yes it is possible, consider using attribute directives. For example to apply some class to a div based on some boolean value use this syntax in div: div [class.some_class]="isActive".

If you want to choose it's content based on some value consider using *ngIf structural directive (or ngSwitch). For example <div> <h1 *ngIf="isActive">I'm ActiveM</h1> </div>

Read more here: https://angular.io/guide/attribute-directives

Also if you have list of some classes and correspoding boolean values that define whether the class is used or not in your controller style, then use following:

in your ts file:

this.currentClasses =  {
    'saveable': this.canSave,
    'modified': !this.isUnchanged,
    'special':  this.isSpecial
  };

in template file use ngClass:

<div [ngClass]="currentClasses">This div is initially saveable, unchanged, and special</div>

Code is from: https://angular.io/guide/template-syntax#ngclass

komron
  • 2,267
  • 2
  • 17
  • 26
1

Use conditional class:

<div class="col-md-3" (click)="isActive = !isActive">
    <div class="center">
        <i class="fa fa-calendar"></i><br>
        <span [class]="isActive? 'classA': 'classB'">Activate</span>
    </div>
</div>
Shailendra Pal
  • 123
  • 1
  • 6