Select Multiple: setValue doesn't work in Angular

96 views Asked by At

I'm trying with no result to set a value to a multiple select when page loads. I'm using Angular 15 (but same problem with 14).

I have a select in HTML file written as follows:

<select formControlName="archivio" class="form-control" id="archivio" required multiple>
   <option value="444">444</option>
   <option *ngFor="let archivio of archivi" [value]="archivio.id_archivio" >
      {{archivio.archivio}}
   </option>
</select>

In component file, I have the following code to set the value to the select:

public modificaSoggettoForm = new FormGroup({
    archivio: new FormControl([''], Validators.required)
}
this.modificaSoggettoForm.controls['archivio'].setValue(['444', soggetto.id_archivio])

Inspecting page with Debugger I see that select value attribute is set for each option to a value like below:

value="2: 3"

where the first token should be the index and the second the real value. The setValue line reported above sets only the value '444' and not the value retrieved from the soggetto.id_archivio field. The value for this field is retrieved correctly but not set on the select. Multiple select set

I tried to change [value] with [ngValue] but the behaviour is the same. The 'value' attribute of the select contains always a value like 'index: value' and 'setValue' doesn't work. Is there a soluton to this? Thank you.

0

There are 0 answers