Angular 6中form.reset()后保留select字段占位符的问题
Hey there! The issue you're facing happens because when you call form.reset(), Angular resets the ngModel bound variables (membership and state) to their initial values. If those variables weren't aligned with your placeholder option's ngValue, the reset won't re-select the placeholder text. Here are a couple of straightforward fixes:
Solution 1: Manually Reset Model Values Alongside Form Reset
Instead of just calling form.reset() in your clear button, explicitly set the bound variables back to undefined to match the placeholder option's value:
Update your clear button's click handler:
<button type="button" class="btn btn-secondary btn-fw" (click)="form.reset(); membership = undefined; state = undefined">Clear</button>
This ensures that after the form resets, the model values align with the placeholder option's [ngValue]="undefined", so the placeholder text reappears immediately.
Solution 2: Align Placeholder Value with Angular's Default Reset State
Angular defaults to resetting template-driven form controls to null if no initial value is set. You can adjust your placeholder to match this behavior for a cleaner setup:
- Update both select placeholder options in your template:
<!-- Membership select placeholder --> <option [ngValue]="null" disabled selected hidden> Please select one option </option> <!-- State select placeholder --> <option [ngValue]="null" disabled selected hidden> Please select one option </option>
- In your component class, initialize the bound variables to
null(or leave them uninitialized, since TypeScript defaults toundefined, but Angular will reset tonullanyway):
membership: string | null = null; state: string | null = null; statesList: string[] = ["Your", "State", "Options"]; // Replace with your actual state list
Now when you call form.reset(), Angular will reset the variables back to null, which matches the placeholder option's ngValue, so the placeholder stays visible after reset without extra manual assignments.
Quick Breakdown of the Root Cause
Your initial setup uses [ngValue]="undefined" for the placeholder, but Angular's form.reset() resets template-driven form controls to null by default (even if your variables were uninitialized). This mismatch between null and undefined is why the placeholder disappears after reset. By either explicitly setting variables to undefined on reset, or aligning the placeholder's value with Angular's default reset state, you fix the mismatch and keep the placeholder visible.
内容的提问来源于stack exchange,提问作者Abhiz

