'How to have if condition for css class?

When editing my component, the column grids also are changed.

Currently, I have this for my edit-component.html

      <div class="col-6" *ngIf="!edit">
        Column1
      </div>
      <div class="col-12 col-md-4 col-sm-2" *ngIf="edit">
        Column1
      </div>
      <div class="col-6" *ngIf="!edit">
        Column2
      </div>
      <div class="col-12 col-md-4 col-sm-2" *ngIf="edit">
        Column2
      </div>

And I have this for edit-component.ts

    edit: boolean = false;

This method works and the css is changing when editting or readonly. But is there other way that I can have if condition for col-12 col-md-5 and col-6?



Solution 1:[1]

Yes. Using the NgClass directive, you can apply classes dynamically based on conditions in your typescript class.

For example: Typescript:

get columnClassDef() {
  return {
    'col-6': !this.edit,
    'col-12 col-md-4 col-sm-2': this.edit,
  };
}

Html:

<div [ngClass]="columnClassDef">
  Column1
</div>
<div [ngClass]="columnClassDef">
  Column2
</div>

NgClass will apply the key of the object as a css class on the element, if the value evaluates to true. It doesn't add the class if the value evaluates to false.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mfaith