Home > Enterprise >  How to use ngModel and ngClass simultaneously in Angular
How to use ngModel and ngClass simultaneously in Angular

Time:09-24

I am using the below code in Angular 6 with Visual Studio Code

<div [ngClass]="{'disabled': isReadOnly}">
    <label class="switch">
        <input type="checkbox" name="Gender" formControlName="Gender"/>
    </label>
</div>

Here isReadOnly is a boolean variable in typescript file

When this value of isReadOnly changes in the typescript file, how it should reflect in the front end?

Here I want to combine ngClass with ngModel.

Any help would be greatly appreciated.

CodePudding user response:

For applying conditional CSS classes you can implement the following,

  • In your component.html file
<div [ngClass]="applyStyles()">
  <label class="switch">
        <input type="checkbox" name="Gender" formControlName="Gender"/>
    </label>
</div>
  • In your component.ts file
applyStyles() {
  let styleClass = {
    'disabled': true // Additional CSS classes can be added to this object, if required.
  }
  if (this.isReadOnly) {
    return styleClass;
  }
}
  • Related