I have an array of objects, say
const countries = [
{
"country": "Afghanistan",
"region": "Asia"
},
{
"country": "Albania",
"region": "Europe"
},
{
"country": "Algeria",
"region": "Africa"
}
];
I have 2 input fields, Country and Region. If user selects the country using select option, I need my region field to be automatically set to the corresponding region of that object.
<div class="form-group stylingtext mt-3">
<label for="" class="pb-2">Movie Country</label>
<select
class="form-select"
aria-label="Default select example"
formControlName="movie_country"
>
<option
*ngFor="let country of countries"
[value]="country.country"
>
{{country.country}}
</option>
</select>
</div>
<div class="form-group stylingtext mt-3">
<label for="" class="pb-2">Movie Region</label>
<input
class="form-control rounded-5"
formControlName="movie_region"
required
>
</div>
I also tried (change) event in select and used ngmodel in the region input-area. But it doesn't work. Can anyone help me with this?
ex: If I select "Algeria" in the country, I want "Africa" in the region input-area.
You can try watch for the country value changes like that:
private destroy$ = new Subject<void>();
ngOnInit(): void {
this.formGroup.controls.movie_country.valueChanges.pipe(
takeUntil(this.destroy$),
).subscribe(
country => this.formGroup.controls.movie_region.patchValue(country.region)
)
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
Where formGroup is name of your FormGroup control. And use subject destroy$ to cancel your subscription.