Say Goodbye to Setters and Getters: Angular???s Transform Option for Input Values

Starting from Angular v16.1.0, a new helpful feature has been introduced to provide an alternative and easy way to transform input values, eliminating the need for using setter and getter methods.

The @Input decorator now includes a transform option, which accepts a function that takes the passed input value and returns a new value. Let's consider a common example:

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;
}

In the above code snippet, when we use the FooComponent and pass the width input as a string:

<app-foo width="100" />

The transformer function toNumber will handle the coercion, converting the string value to a number.

Another scenario where this feature comes in handy is when dealing with HTML attributes. boolean attributes are considered true if they are present on a DOM node and false 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:

Website