Performance: Showing validation errors
This affects interaction responsiveness and visual stability when users input data and see validation feedback.
template: `<input [(ngModel)]="name" (blur)="validateName()" /> <div [style.visibility]="showError ? 'visible' : 'hidden'">Name is required</div>`; component: { name = ''; showError = false; validateName() { this.showError = !this.name || this.name.length === 0; } }
template: `<input [(ngModel)]="name" /> <div *ngIf="!nameValid">Name is required</div>`; component: { get nameValid() { return this.name && this.name.length > 0; } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Validation on every keystroke with *ngIf | High (many DOM toggles) | Multiple reflows per input | High paint cost due to layout shifts | [X] Bad |
| Validation on blur with visibility toggle | Low (few DOM changes) | Single reflow on blur | Low paint cost, stable layout | [OK] Good |
touched or dirty flags help detect user interaction before showing errors.*ngIf is used to conditionally display content based on an expression.myControl.invalid && myControl.touched to show errors only when invalid and user touched the field.<input [formControl]="emailControl"> <div *ngIf="emailControl.invalid && emailControl.touched"> <small *ngIf="emailControl.errors?.required">Email is required.</small> <small *ngIf="emailControl.errors?.email">Invalid email format.</small> </div>
required error is true, but email error is false because empty triggers required first.required error message is shown because emailControl.errors?.required is true.<div *ngIf="emailControl.errors.required">Email is required.</div>
touched is important.errors.required but not if the user touched the field, so error stays hidden initially.invalid and touched to avoid showing errors prematurely.passwordControl.errors?.minlength inside the conditional block to display the custom message.Pass the test and this pattern moves unknown