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

Tram Ho

Today I will bring you a very interesting and useful article. Have you ever had trouble using setter and getter methods in Angular? Rest assured, from Angular v16.1.0, an extremely useful new feature has been introduced that provides an easy and alternative approach to transformation – Transform input values, thereby removing need to use setter and getter methods. Does it sound appealing?

Problem with Setters and Getters

To better understand, first, let’s learn about setter and getter . In object-oriented programming, setter and getter are methods used to set and get the value of properties. However, their use can sometimes cause unnecessary troubles.

For example, consider the code below:

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

The toNumber conversion function will handle the conversion, converting string values ​​to numbers.

For programmers who are new or unfamiliar with this way of working, having to use setter and getter methods can get complicated and confusing.

Solution from Angular v16.1.0

Okay, so where’s the solution? That’s the new feature of Angular: transform option. With transform option, you can easily transform input values ​​without having to use setter and getter . Consider a specific example below.

The code below illustrates how to use transform option:

In the above code, the booleanAttribute conversion function is used to handle the boolean conversion. Now, when we use CheckboxComponent and specify the disabled attribute:

The conversion function will properly interpret the presence of the property as true .

Notably, Angular already uses this feature internally in router.

Solution for HTML attributes

Likewise, transform option can also help us solve problems with HTML attributes. If you’ve ever worked with Angular, you’ve probably had the problem that Angular interprets all static properties as strings, which leads to a common problem. For example, the following code will return an empty string:

To solve this problem, we can use transform option instead of using getter and setter methods.

summary

Overall, with the introduction of transform option in the @Input decorator, Angular has simplified the input value conversion process, providing a more streamlined approach compared to traditional setter and getter methods.

Share the news now

Source : Viblo