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?
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
Did you try doing this? https://stackblitz.com/edit/angular-ngclass-nbleik
<div [class]="inputBlockClass" [ngClass]="showLabel?inputBlockExtraClass:''">>
sometext
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With