8

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?

1
  • I'd remove [class] and use [ngClass]="[inputBlockClass, showLabel ? inputBlockExtraClass : '']". Commented Mar 28, 2020 at 19:28

2 Answers 2

11

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

Sign up to request clarification or add additional context in comments.

1 Comment

your solution of getting rid of class is nice.I learnt something new. Thanks
5

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

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

1 Comment

Show some support by upvoting whenever you found it useful ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.