- vừa được xem lúc

Blog#272: Say Goodbye to Setters and Getters: Angular’s Transform Option for Input Values (Song ngữ: VN - EN - JP)

0 0 15

Người đăng: NGUYỄN ANH TUẤN

Theo Viblo Asia

Hi các bạn, mình là TUẤN. Hiện đang là một Full-stack Web Developer tại Tokyo😊. Hãy follow blog của mình để không bỏ lỡ những bài viết hữu ích và thú vị trong tương lại nhé.

Nếu bạn thích bài viết, xin hãy cho mình 1 upvote và đăng ký để ủng hộ mình có thêm động lực ra thêm nhiều bài viết hay hơn trong tương lại nhé.😊

Hôm nay mình sẽ mang đến cho các bạn một bài viết vô cùng thú vị và bổ ích. Bạn có bao giờ gặp rắc rối khi phải sử dụng các phương thức settergetter trong Angular không? Hãy yên tâm, từ phiên bản Angular v16.1.0, một tính năng mới cực kỳ hữu ích đã được giới thiệu nhằm cung cấp một cách tiếp cận dễ dàng và thay thế để chuyển đổi - Transform các giá trị input, từ đó loại bỏ nhu cầu phải sử dụng các phương thức settergetter. Nghe hấp dẫn chưa nào?

Vấn đề với Setters và Getters

Để hiểu rõ hơn, trước hết, chúng ta cùng tìm hiểu về settergetter nhé. Trong lập trình hướng đối tượng, settergetter là những phương thức được sử dụng để thiết lập và lấy giá trị của các thuộc tính. Tuy vậy, việc sử dụng chúng đôi khi có thể gây ra những phiền toái không đáng có.

Ví dụ, xem xét đoạn mã dưới đây:

function toNumber(value: string | number) { return isNumber(value) ? value : parseInt(value);
} @Component({ selector: 'app-foo', template: ``, standalone: true,
})
export class FooComponent { @Input({ transform: toNumber }) width: number;
}

Trong đoạn mã trên, khi chúng ta sử dụng FooComponent và truyền width input dưới dạng một chuỗi:

<app-foo width="100" />

Hàm chuyển đổi toNumber sẽ xử lý việc chuyển đổi, chuyển đổi giá trị chuỗi thành số.

Đối với những lập trình viên mới hoặc chưa quen với cách làm việc này, việc phải sử dụng các phương thức settergetter có thể trở nên phức tạp và gây rối.

Giải pháp từ Angular v16.1.0

Rồi, vậy giải pháp ở đâu? Đó chính là tính năng mới của Angular: transform option. Với transform option, bạn có thể dễ dàng chuyển đổi các giá trị input mà không cần phải sử dụng settergetter. Hãy xem xét một ví dụ cụ thể dưới đây.

Đoạn mã dưới đây minh họa cách sử dụng transform option:

import { Input, booleanAttribute } from '@angular/core'; @Component({ selector: 'app-checkbox', template: ``, standalone: true,
})
export class CheckboxComponent { @Input({ transform: booleanAttribute }) disabled: boolean = false;
}

Trong đoạn mã trên, hàm chuyển đổi booleanAttribute được sử dụng để xử lý việc chuyển đổi boolean. Bây giờ, khi chúng ta sử dụng CheckboxComponent và chỉ định thuộc tính disabled:

<app-checkbox disabled />

Hàm chuyển đổi sẽ diễn giải đúng mực sự hiện diện của thuộc tính như true.

Đáng chú ý là Angular đã sử dụng tính năng này một cách nội tại trong router.

Giải pháp cho các thuộc tính HTML

Cũng như vậy, transform option cũng có thể giúp chúng ta giải quyết vấn đề với các thuộc tính HTML. Nếu bạn đã từng làm việc với Angular, có lẽ bạn đã từng gặp vấn đề khi Angular hiểu tất cả các thuộc tính tĩnh dưới dạng chuỗi, dẫn đến một vấn đề phổ biến. Ví dụ, đoạn mã sau đây sẽ trả về một chuỗi rỗng:

@Component({ selector: 'app-checkbox', template: ``, standalone: true,
})
export class CheckboxComponent { @Input() disabled: boolean;
}
<app-checkbox disabled />

Để giải quyết vấn đề này, chúng ta có thể sử dụng transform option thay cho việc sử dụng các phương thức gettersetter.

Tổng kết

Nhìn chung, với việc giới thiệu transform option trong decorator @Input, Angular đã đơn giản hóa quá trình chuyển đổi giá trị input, mang lại một cách tiếp cận tinh gọn hơn so với các phương thức settergetter truyền thống.


English Version

Today I'm going to bring you a very interesting and informative article. Have you ever encountered any trouble using the setter and getter methods in Angular? Don't worry, starting from Angular version 16.1.0, a new and incredibly useful feature has been introduced to provide an easy and alternative way to transform input values, eliminating the need for setter and getter methods. Sounds appealing, doesn't it?

The Issue with Setters and Getters

To understand better, let's first familiarize ourselves with setter and getter. In object-oriented programming, setter and getter are methods used to set and get the values of properties. However, using them can sometimes cause unnecessary complications.

For example, consider the following code snippet:

function toNumber(value: string | number) { return isNumber(value) ? value : parseInt(value);
} @Component({ selector: 'app-foo', template: ``, standalone: true,
})
export class FooComponent { @Input({ transform: toNumber }) width: number;
}

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

<app-foo width="100" />

The toNumber transformation function will handle the conversion, transforming the string value into a number.

For new or unfamiliar developers, using setter and getter methods can be complex and confusing.

The Solution from Angular v16.1.0

So, where's the solution? It lies in a new feature introduced by Angular: the transform option. With the transform option, you can easily transform input values without the need for setter and getter methods. Let's consider a specific example below.

The following code snippet illustrates the usage of the transform option:

import { Input, booleanAttribute } from '@angular/core'; @Component({ selector: 'app-checkbox', template: ``, standalone: true,
})
export class CheckboxComponent { @Input({ transform: booleanAttribute }) disabled: boolean = false;
}

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

<app-checkbox disabled />

The transformation function will interpret the presence of the attribute as true.

It's worth noting that Angular has internally used this feature in the router.

Solution for HTML Attributes

Similarly, the transform option can help us address issues with HTML attributes as well. If you've worked with Angular before, you may have encountered the problem of Angular interpreting all static attributes as strings, leading to a common issue. For example, the following code snippet would return an empty string:

@Component({ selector: 'app-checkbox', template: ``, standalone: true,
})
export class CheckboxComponent { @Input() disabled: boolean;
}
<app-checkbox disabled />

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

Summary

In conclusion, by introducing the transform option in the @Input decorator, Angular has simplified the process of transforming input values, providing a more streamlined approach compared to traditional setter and getter methods.


日本語版

今日は、非常に興味深く、有益な記事をお届けします。Angularでsettergetterメソッドを使用する際にトラブルに遭遇したことはありますか?心配しないでください、Angularバージョン16.1.0から、新しく非常に便利な機能が導入され、入力値を簡単に変換するための代替方法が提供されるようになりました。良かったですね。

setterとgetterの問題

より良く理解するために、まずはsettergetterに慣れてみましょう。オブジェクト指向プログラミングでは、settergetterはプロパティの値を設定および取得するために使用されるメソッドです。しかし、使用することで不必要な複雑さが生じることがあります。

例えば、次のコードの断片を考えてみましょう:

function toNumber(value: string | number) { return isNumber(value) ? value : parseInt(value);
} @Component({ selector: 'app-foo', template: ``, standalone: true,
})
export class FooComponent { @Input({ transform: toNumber }) width: number;
}

上記のコードの断片では、FooComponentを使用してwidth入力を文字列として渡す場合:

<app-foo width="100" />

toNumber変換関数が変換を処理し、文字列値を数値に変換します。

新しいまたは慣れていない開発者にとって、settergetterメソッドを使用することは複雑で混乱することがあります。

Angular v16.1.0からの解決策

では、解決策はどこにあるのでしょうか?それは、Angularによって導入された新機能にあります:transformオプションです。transformオプションを使用すると、settergetterメソッドを使用せずに入力値を簡単に変換することができます。以下に具体的な例を考えてみましょう。

次のコードの断片は、transformオプションの使用例を示しています:

import { Input, booleanAttribute } from '@angular/core'; @Component({ selector: 'app-checkbox', template: ``, standalone: true,
})
export class CheckboxComponent { @Input({ transform: booleanAttribute }) disabled: boolean = false;
}

上記のコードの断片では、booleanAttribute変換関数がブール値の変換を処理するために使用されています。今、CheckboxComponentを使用してdisabledプロパティを指定すると:

<app-checkbox disabled />

変換関数は属性の存在をtrueと解釈します。Angularは、内部的にこの機能をルーターで使用していることに注意する価値があります。

HTML属性の解決策

同様に、transformオプションはHTML属性の問題に対処するのに役立ちます。Angularを使用したことがある場合、すべての静的属性を文字列として解釈するAngularの問題に遭遇したことがあるかもしれません。次のコードの断片では、空の文字列が返されます:

@Component({ selector: 'app-checkbox', template: ``, standalone: true,
})
export class CheckboxComponent { @Input() disabled: boolean;
}
<app-checkbox disabled />

この問題を解決するために、gettersetterメソッドの代わりにtransformオプションを使用することができます。

まとめ

結論として、@Inputデコレーターでtransformオプションを導入することにより、Angularは入力値の変換プロセスを簡素化し、従来のsettergetterメソッドに比べてより効率的なアプローチを提供しています。

Cuối cùng

Như thường lệ, mình hy vọng bạn thích bài viết này và biết thêm được điều gì đó mới.

Nếu bạn thích bài viết, xin hãy cho mình 1 upvote và đăng ký để ủng hộ mình có thêm động lực ra thêm nhiều bài viết hay hơn trong tương lại nhé.

Cảm ơn và hẹn gặp bạn trong những bài viết tiếp theo. Thank you. 😊


Bạn muốn làm Dev hoặc BrSE tại Nhật (N3-N4, 1-2 năm exp trở lên hoặc zero tech có tiếng N1-N2, cả 2 đầu Nhật và VN) cần mình đưa roadmap hoặc review CV, hiểu hơn về các câu hỏi thường gặp khi interview Dev hoặc BrSE, cách deal lương cao... cần support thì cứ liên hệ mình qua zalo nhé: 0379302361 hoặc Facebook của mình. free

Ref

Bình luận

Bài viết tương tự

- vừa được xem lúc

Route in Angular JS

Router là một module được đặt tại @angular/router, cung cấp cho ứng dụng Angluar của chúng ta khả năng điều hướng và hiển thị nội dung phù hợp với địa chỉ URL. Với các ứng dụng web thông thường, việc điều hướng theo URL thường sẽ do phía server đảm nhiệm, giống như hình ảnh dưới đây là ví dụ với Rai

0 0 84

- vừa được xem lúc

Có gì mới trong Angular 11

Phiên bản Angular 11.0.0 được phát hành vào tháng 11 năm 2020. Bản phát hành chính Angular 11 cung cấp các bản cập nhật trên toàn bộ nền tảng, bao gồm CLI và các components.

0 0 89

- vừa được xem lúc

Pipe trong Angular

Xin chào tất cả mọi người, bài viết này minh xin giới thiệu về Pipe trong Angular, rất mong được mọi người theo dõi. 1) Pipe trong Angular là gì. . .

0 0 113

- vừa được xem lúc

Angular Reactive Forms: Cách sử dụng FormArray

Trong bài viết này chúng ta sẽ tìm hiểu khi nào và cách sử dụng FormArray, cả trong Component và trong Template, ngoài ra chúng ta sẽ xem cách để custom validation cho nó. Vì sao chúng ta cần sử dụng FormArray.

0 0 92

- vừa được xem lúc

RxJS và Reactive Programming

1 - Stream. Streams are a sequence of values over time.

0 0 341

- vừa được xem lúc

Mapping class Java với Angular Typescript model – Chưa bao giờ dễ đến thế

Xin chào mọi người hôm nay mình giới thiệu một loại đồ chơi cực xịn cực hay ho luôn, đây là một thư viện giúp cho mọi người tạo ra 1 class Typescript trong dự án Frontend ở đây mình lấy ví dụ là Angul

0 0 81