Performance: Form validation with template attributes
This affects the interaction responsiveness and rendering speed during user input in forms.
<input name="email" ngModel required minlength="5">
<input name="email" ngModel required minlength="5" (input)="validateEmail($event.target.value)">
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Custom input event validation | High (many event handlers) | Multiple per keystroke | High due to frequent style updates | [X] Bad |
| Template attribute validation | Low (native attributes) | Single per input | Low, minimal style recalculations | [OK] Good |
required or minlength in Angular forms?required and minlength are used in the HTML to set validation rules simply and declaratively.required attribute is a standard HTML attribute used as required without brackets or extra directives.required alone is correct.required attribute for required fields [OK]<input type="text" name="username" ngModel required minlength="4" #usernameRef="ngModel"> <div *ngIf="usernameRef.invalid && usernameRef.touched"> <small *ngIf="usernameRef.errors?.required">Username is required.</small> <small *ngIf="usernameRef.errors?.minlength">Minimum 4 characters.</small> </div>
usernameRef.invalid and usernameRef.touched are true, only the minlength error message appears.<input type="email" name="email" ngModel required #emailRef> <div *ngIf="emailRef.invalid && emailRef.touched"> <small *ngIf="emailRef.errors.required">Email is required.</small> <small *ngIf="emailRef.errors.email">Invalid email format.</small> </div>
#emailRef is used to access validation state, but it lacks the export ="ngModel" which is needed to access invalid and errors.required attribute is correct as is, AND logic for showing errors is appropriate, and input type "email" is valid for email validation.<form #myForm="ngForm"> <input name="email" ngModel required email> <button type="submit" [disabled]="???">Submit</button> </form>
??? to disable the button until the form is valid?invalid which is true when the form is not valid, and valid which is true when valid.myForm.invalid is true means the button is disabled until the form becomes valid. Using myForm.valid would disable when valid (incorrect). Other options relate to touch or pristine state, not validity.Pass the test and this pattern moves unknown