I have a problem when I want to update the selected value of a select input with my typescript code. I have not found anything related to this as the problem is quite specific.
In my example, I want to have a select input for a list of countries. But this input can be updated dynamically since the last option allows you to add a new country.
Here is the HTML file :
<label for="select_country">Pays</label>
<select [(ngModel)]="selectedCountry"
id="select_country"
(change)="check_country()">
<option *ngFor="let country of countries" >{{ country }}</option>
<option >Nouveau pays</option>
</select>
{{ selectedCountry }}
The associated typescript file :
import { Component, OnInit } from '@angular/core';
import { CountriesService } from "../country.service"
@Component({
selector: 'app-add-recette',
templateUrl: './add-recette.component.html',
styleUrls: ['./add-recette.component.css']
})
export class AddRecetteComponent implements OnInit {
selectedCountry : string = "";
countries : string [] = [];
constructor(private countriesService: CountriesService) { }
ngOnInit() {
this.getCountries();
}
getCountries() : void{
this.countriesService.getCountries()
.subscribe(string => this.countries = string);
}
check_country() : void {
if (this.selectedCountry === "Nouveau pays") {
this.selectedCountry = "";
let new_country = prompt("New country ?").trim();
if (new_country && new_country.length > 0) {
this.countriesService.add(new_country);
this.selectedCountry = new_country;
}
}
}
}
And finally, the service, quite short :
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class CountriesService {
countries : string [] = [
"France", "Chine", "Nouvelle-Zélande"
]
constructor() { }
getCountries(): Observable<string[]> {
return of(this.countries);
}
add(newC : string) : void {
if (!(this.countries.includes(newC))) {
this.countries.push(newC);
}
}
}
The problem is :
When I try to select a country, it's fine.
When I try to add a new country, it's fine.
When from France, I try to add China, it detects that it is already in the array, so it doesn't add it and just point to China, so it's fine.
But when from France, I try to add France, the selectedCountry is updated to France so it's ok but the select option now shows us Nouveau pays
which is not what it is supposed to do since this.selectedCountry
equals France.
More generally, adding a country that is already in the list doesn't update the select input if the select input was previously on it.
I have found this but the solution given doesn't work with me.
The behaviour is very surprising. What do you think about it ?
Thank you very much for your help