Say Goodbye to Setters and Getters: Angular’s Transform Option for Input Values
<p>Starting from Angular v16.1.0, a new helpful feature has been introduced to provide an alternative and easy way to <strong>transform</strong> input values, eliminating the need for using <code>setter</code> and <code>getter</code> methods.</p>
<p>The <code>@Input</code> decorator now includes a <code>transform</code> option, which accepts a function that takes the passed <code>input</code> value and returns a new value. Let's consider a common example:</p>
<pre>
function toNumber(value: string | number) {
return isNumber(value) ? value : parseInt(value);
}
@Component({
selector: 'app-rect',
template: ``,
standalone: true,
})
export class FooComponent {
@Input({ transform: toNumber }) width: number;
}</pre>
<p>In the above code snippet, when we use the <code>FooComponent</code> and pass the <code>width</code> input as a string:</p>
<pre>
<app-foo width="100" /></pre>
<p>The transformer function <code>toNumber</code> will handle the coercion, converting the string value to a number.</p>
<p>Another scenario where this feature comes in handy is when dealing with HTML attributes. <code>boolean</code> attributes are considered <code>true</code> if they are present on a DOM node and <code>false</code> if they are omitted. However, Angular interprets all static attributes as strings, leading to a common issue. For example, the following code would return an empty string:</p>
<p><a href="https://netbasal.com/say-goodbye-to-setters-and-getters-angulars-transform-option-for-input-values-88fd9442dcad">Website</a></p>