I want to have a select with options that are read from other inputs and when the input changes, my selection will change too.
All select and inputs are reactive forms. The problem is when I change the value of the inputs, the select options only update when I set the options value to the form control. If I set the options value to the value of form control, they don't get updated.
Example code is here: https://stackblitz.com/edit/angular-5zfocw
Template:
<form [formGroup]="form">
<div formArrayName="opts" *ngFor="let opt of form.get('opts').controls; let i = index">
<div [formGroupName]="i">
{{i}}:
<input type="text" formControlName="name">
</div>
</div>
</form>
<form [formGroup]="form">
<label> Selection:</label>
<select formControlName="selection">
<option *ngFor="let opt of form.get('opts').controls; let i=index" [value]="opt.value.name">
{{opt.value.name}}
</option>
</select>
</form>
<hr>
<pre>
selection: {{ form.get('selection').value | json}}
</pre>
Compoent:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
public form: FormGroup
constructor(private fb: FormBuilder){
this.form = this.fb.group({
opts: this.fb.array([
this.fb.group({name: ['N0']}),
this.fb.group({name: ['N1']}),
this.fb.group({name: ['N2']})
]),
selection: [{value: {}}]
})
}
}
If I change line 13 in the HTML template to:
<option *ngFor="let opt of form.get('opts').controls; let i=index" [value]="opt">
Then the option and the input is sync perfectly. However, I am not able to get the value of the selection.
If the line is change back to [value]="opt.value.name", then select N2, then change N2 input, my selection will be lost and the value does not update.
what I want
I want 1. Select N2 from drop down. 2. Change N2 to something else such as N22 in input. 3. The selection should update to N22. And the value N22 should be displayed at the bottom of the page.
What should I do?