Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add CSS class name from variable in Angular 9 depends on boolean variable?

I want to add class names from a variable, but it's depends on another variable in Angular 9.

Here is my TypeScript code

export class InputComponent implements OnInit {
  @Input() inputBlockClass = 'col-12 d-flex px-0';
  @Input() inputBlockExtraClass = 'col-md-9';
  @Input() showLabel = true;

  // ...
}

Here is my HTML code:

<div [class]="inputBlockClass" [class.inputBlockExtraClass]="showLabel">

I tried this too, but it's doesn't work:

<div [class]="inputBlockClass" [ngClass]="{inputBlockExtraClass: showLabel}">

Both solution give this result:

<div _ngcontent-sxj-c111="" class="col-12 d-flex px-0 inputBlockExtraClass">

But I want this:

<div _ngcontent-sxj-c111="" class="col-12 d-flex px-0 col-md-9">

How can I add a class name from variable depends on boolean variable?

like image 760
netdjw Avatar asked Mar 28 '20 19:03

netdjw


2 Answers

You can do it like this:

<div [class]="inputBlockClass" [ngClass]="showLabel ? inputBlockExtraClass : ''">

or you can get rid of [class]:

<div [ngClass]="[inputBlockClass, showLabel ? inputBlockExtraClass : '']">

STACKBLITZ DEMO

like image 103
developer033 Avatar answered Sep 30 '22 08:09

developer033


Did you try doing this? https://stackblitz.com/edit/angular-ngclass-nbleik

 <div [class]="inputBlockClass" [ngClass]="showLabel?inputBlockExtraClass:''">>
      sometext
 </div>
like image 44
M A Salman Avatar answered Sep 30 '22 10:09

M A Salman