DEV Community

Saunak Surani
Saunak Surani

Posted on

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

In Angular, input properties are used to pass data from a parent component to a child component. The @Input decorator is used to define input properties.

Traditionally, input properties have been transformed using setter and getter methods. However, 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 transform option

The @Input decorator now includes a transform option, which accepts a function that takes the passed input value and returns a new value. For example, the following code shows how to use the transform option to convert a string value to a number:

import { Input } from '@angular/core';

@Component({
  selector: 'app-rect',
  template: ``,
  standalone: true,
})
export class FooComponent {
  @Input({ transform: toNumber }) width: number;
}

function toNumber(value: string | number) {
  return isNumber(value) ? value : parseInt(value);
}
Enter fullscreen mode Exit fullscreen mode

In the above code, the toNumber function is used to transform the input value. If the input value is a string, the toNumber function will convert it to a number. If the input value is already a number, the toNumber function will simply return the value.

Benefits of using the transform option

There are a few benefits to using the transform option instead of using setter and getter methods.

  • The code is cleaner. The transform option allows you to write cleaner code by eliminating the need for setter and getter methods.
  • The code is more maintainable. The transform option makes the code more maintainable by making it easier to understand how the input value is being transformed.
  • The code is more extensible. The transform option makes the code more extensible by allowing you to easily customize the transformation logic.

Conclusion

The transform option is a new and helpful feature in Angular that can be used to simplify the process of transforming input values. The transform option allows you to write cleaner, more maintainable, and more extensible code.

Top comments (0)