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&nbsp;<strong>transform</strong>&nbsp;input values, eliminating the need for using&nbsp;<code>setter</code>&nbsp;and&nbsp;<code>getter</code>&nbsp;methods.</p> <p>The&nbsp;<code>@Input</code>&nbsp;decorator now includes a&nbsp;<code>transform</code>&nbsp;option, which accepts a function that takes the passed&nbsp;<code>input</code>&nbsp;value and returns a new value. Let&#39;s consider a common example:</p> <pre> function toNumber(value: string | number) { return isNumber(value) ? value : parseInt(value); } @Component({ selector: &#39;app-rect&#39;, template: ``, standalone: true, }) export class FooComponent { @Input({ transform: toNumber }) width: number; }</pre> <p>In the above code snippet, when we use the&nbsp;<code>FooComponent</code>&nbsp;and pass the&nbsp;<code>width</code>&nbsp;input as a string:</p> <pre> &lt;app-foo width=&quot;100&quot; /&gt;</pre> <p>The transformer function&nbsp;<code>toNumber</code>&nbsp;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.&nbsp;<code>boolean</code>&nbsp;attributes are considered&nbsp;<code>true</code>&nbsp;if they are present on a DOM node and&nbsp;<code>false</code>&nbsp;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>