Home > OS >  How to have if condition for css class?
How to have if condition for css class?

Time:05-17

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

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

      <div  *ngIf="!edit">
        Column1
      </div>
      <div  *ngIf="edit">
        Column1
      </div>
      <div  *ngIf="!edit">
        Column2
      </div>
      <div  *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?

CodePudding user response:

You can use the ngClass directive.

<div [ngClass]="{'col-6': !edit, 'col-sm-2 col-md-4 col-12': edit}">
    Column1
</div>

CodePudding user response:

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.

  • Related