Scenario
Our Angular hello
component has a responsive
boolean @Input
property . When responsive
is added to a component declaration, we want the responsive
property to be true
.
Thus if we declare hello
like this.
<hello></hello>
Then responsive
will be false
. But if we declare it like this it will be true
.
<hello responsive></hello>
Approach
We will use Angular CDK coerceBooleanProperty
function to perform the coercion.
Note that if you are on Angular 16.1+ you can also use booleanAttribute
from @angular/core
. We provide another demo of that at the end of the article.
After importing the coerceBooleanProperty
method like this.
import { coerceBooleanProperty } from '@angular/cdk/coercion';
We can invoke it using an input transform like this.
@Input({ transform: coerceBooleanProperty }) responsive: boolean = false;
Demo
Angular 16.1+ Demo
With Angular 16.1+
you can use booleanAttribute
from @angular/core
to do the same thing.
Related Concepts
Previously what we did with the transform
could be accomplished using a setter
.