Performance: ngForm directive and form state
This affects how Angular tracks form input changes and validation, impacting interaction responsiveness and rendering updates.
<form ngForm #formRef="ngForm" (ngSubmit)="onSubmit(formRef)"> <input name="email" ngModel /> <input name="password" ngModel /> <button type="submit">Submit</button> </form>
<form #formRef="ngForm"> <input name="email" [(ngModel)]="email" (ngModelChange)="onChange()" /> <input name="password" [(ngModel)]="password" (ngModelChange)="onChange()" /> </form>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Using (ngModelChange) on every input | Many event handlers attached | Multiple reflows per keystroke | Higher paint cost due to frequent updates | [X] Bad |
| Using ngForm with ngModel and submit event | Minimal event handlers | Single reflow on submit | Lower paint cost with batched updates | [OK] Good |
ngForm directive do in Angular?ngFormngForm directive is used to track the state of a form and its inputs in Angular.ngForm does not dongForm in Angular?ngForm as its value, like #myForm="ngForm".#myForm="ngForm". ... misses the directive name, C misplaces the directive, and D uses incorrect binding syntax.<form #f="ngForm"> <input name="email" ngModel required> <button [disabled]="!f.form.valid">Submit</button> </form>
required attribute, so if empty, the form is invalid.!f.form.valid is true, meaning when the form is invalid.<form #myForm="ngForm"> <input name="username" ngModel> <button [disabled]="myForm.invalid">Submit</button> </form>
required, so it does not make the form invalid when empty.myForm.invalid is valid shorthand for myForm.form.invalid, so no error there.ngForm states to achieve this?myForm.form.invalid is true if form is invalid; myForm.form.dirty is true if user changed any input.Pass the test and this pattern moves unknown