Angular中Select控件结合formControl设置默认选中值问题求助
Hey there! I totally get the frustration when you've tried multiple solutions and still can't get that default option to stick. Let's break down why your current setup isn't working and fix it step by step.
The Root Cause
When you use an object as the value for [ngValue] in your <option> tags, Angular uses reference equality to determine which option should be selected. Your datas.country is a separate object instance, even though its content matches the Luxembourg entry in selOptCountries—so Angular doesn't recognize it as the same option.
Working Solution
Instead of using the datas.country object directly, you need to grab the exact object instance from your selOptCountries array. Here's how to adjust your code:
Update Your Component (.ts) Code
First, find the matching country object from your options array using a unique identifier (like id):
// Assuming datas.country is already available when you initialize the form const defaultSelectedCountry = this.selOptCountries.find(country => country.id === datas.country.id); this.fgForm = this.formBuilder.group({ 'country': [defaultSelectedCountry || null, [Validators.required]], });
If Your Options Load Asynchronously (e.g. from API)
If you're fetching selOptCountries via an API call, make sure you set the default value after the data has loaded:
// Example API call (adjust to match your service) this.yourCountryService.getCountries().subscribe(countries => { this.selOptCountries = countries; // Now find the default country and update the form const defaultCountry = this.selOptCountries.find(c => c.id === datas.country.id); this.fgForm.get('country')?.setValue(defaultCountry); });
Why This Works
By using the object from selOptCountries, you're passing the same reference that Angular uses to track the options in your <select> control. This lets Angular correctly match and select the default option.
Confirm Your Template Is Correct
Your existing template code is already set up properly—no changes needed here! Just to confirm:
<form [formGroup]="fgForm"> <select class="form-control" formControlName="country"> <option value="" [ngValue]="null">Choose your country</option> <option *ngFor="let oneCountry of selOptCountries;" [ngValue]="oneCountry">{{oneCountry.name}}</option> </select> </form>
Quick Notes
- Always use a unique property (like
id) to match objects—avoid relying on name or iso2 since those could have duplicates. - If you ever need to update the selected option later, use
setValue()orpatchValue()on the form control, making sure to pass an object fromselOptCountries.
内容的提问来源于stack exchange,提问作者Jean-Philippe M

