Angular: An Exploration in Triggering Validation and Transformation
bob.ts
Posted on November 8, 2021
Recently, I came across an intriguing article about (Dynamic self-registered FormControl in Angular)(https://medium.com/@toha.marko/dynamic-self-registered-reactive-formcontrol-in-angular-bf2342b7f14d).
Everything about this article was well done and very interesting.
There was one point in the article that spiked my interest: the author triggered the "creation" of the Form Controls dynamically within the Angular HTML.
So, I decided to experiment and see if I could use this as a means to trigger data validation and transformation.
This is an experiment, simple to see if I can do something. Personally, I see some benefit in the pattern. But, this does not mean I am endorsing this as a good pattern or a better means than any other way of doing something.
The working code ...
The Code
Here's the basics of the data.service.ts
...
data: Array<any> = [
{ first: 'Bob', last: 'Fornal' },
{ first: 'Jenny', last: 'Fornal' },
{ first: 'Patrick', last: 'Fornal' },
{ first: 'Anne', last: 'Fornal' }
];
getData = (): Array<any> => this.data;
validate = (item: any): boolean => item.hasOwnProperty('first') && item.hasOwnProperty('last');
transform = (item: any): any => {
let transformed: any = Object.assign({}, item);
if (!transformed.hasOwnProperty('fullname')) {
transformed.fullname = item.last + ', ' + item.first;
}
if (!transformed.hasOwnProperty('checked')) {
transformed.checked = false;
}
console.log(item, transformed);
return transformed;
}
My intent is to ...
- Get the data
- Display a Validation State
- Transform the data significantly
- Display the changes
The app.component.ts
is really simple ...
data: Array<any>;
constructor(
private dataService: DataService
) {
this.data = [ ...this.dataService.getData() ];
}
validate = this.dataService.validate;
transform = this.dataService.transform;
The code simple sets up the data and connects the validate
and transform
functions the the same in the dataService
.
Then, in the HTML (app.component.html
) ...
<div class="individual" *ngFor="let item of data;">
<div>Validated: {{ validate(item) }}</div>
<ng-container *ngIf="transform(item); let transformed">
<div>Fullname: {{ transformed.fullname }}</div>
<div>Status is False: {{ transformed.checked === false }}</div>
</ng-container>
</div>
Looping over the data, it gets validated, transformed, and displayed ... all exactly as expected.
Conclusion
This was a particularly simple experiment. To me, is shows a triggering path when dealing with data that I haven't explored before.
Generally, when I am digging into someone else's code, I am looking at the DOM (the HTML) first. In this case, being able to see the trigger points and validation processes so early could have a huge benefit.
Posted on November 8, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.