0
votes

I know that using function calls in Angular templates is a bad practice. In short it is because Change Detection will make the function run many times, which will lead to bad performance. (This article goes more into depth on the topic)

I have been following this rule closely except from one exception, and that is when I need the value from my Reactive Form in my template. Usually I use it like this:

My way of doing it

Template: <div *ngIf="myFormGroup.get('name').invalid">Filling out name is required</div>

Here I am not following the rule because I am calling the function myFormGroup.get('name') inside my template. To solve this I decided to go to the Angular documentation to see how they do this, and I found a similar example here: https://angular.io/guide/form-validation#built-in-validator-functions.

What the Angular documentation does is that they put the form control in a getter, and then they use the getter in the template, like this:

Angular documentation way of doing it

Component class: get name() { return this.myFormGroup.get('name'); }

Template: <div *ngIf="name.invalid">Filling out name is required</div>

My questions are

  1. Is it ok to use "myFormGroup.get('name')" in a template, even though it breaks the rule of not having function calls in the template?

  2. Is the Angular Documentation way of doing this any different from my way of doing it when it comes to performance? (My understanding is that using a getter this way does noe solve the Change Detection Performance issue)

1

1 Answers

0
votes

You can do like this:

In Template:

<input type="text" id="name" formControlName="name" />
<div *ngIf="isControlInvalid('name')">
 Something
</div>

In Component:

isControlInvalid(controlName: string): boolean {
 const control = this.myForm.controls[controlName];

 const result = control.invalid && control.touched;

 return result;
}