I am using Angular 12 and I have a child component and using the @Input decorator.
So I have something like this:
<hello
isRed="true">
</hello>
Here is the child component:
import { Component, Input } from '@angular/core';
@Component({
selector: 'hello',
template: `<h1 class="{{redClass}}">Test</h1>`,
styles: [`h1 { font-family: Lato; } .red { background: red }`]
})
export class HelloComponent {
redClass;
@Input() isRed: boolean = false;
}
isRed is currently boolean but I want a way to say: if (isRed === true) { redClass = '.red' }
How can I do that?
In the template, just do
<h1 [class.red]="isRed">Test</h1>
This will only apply red
css class if isRed
is truthy.
This approach will also update css if parent component updates the value of isRed
. If you want to follow imperative approach, try to update redClass
variable inside ngOnChanges
instead of ngOnInit
.