I have a <select> tag which needs to bind the multiple attribute to a value in the component. If I do this:
<select [multiple]="multiple" [(ngModel)]="model" id='sel' name='sel'>
<option *ngFor="let option of options" [ngValue]="option.value">{{option.label}} - {{option.value}}</option>
Then I get very quirky behaviour - the page inits with the first item selected, even though the ngModel value is set to a different option item. Also, the bound ngModel can give an array when it is changed, which you would expect with a multiple tag, although I want the tag to be dependent on a boolean value.
Here is a StackBlitz: https://stackblitz.com/edit/angular-ivy-bpvmt2?file=src/app/app.component.html
CodePudding user response:
Presence of [multiple] on select tag results in creation of SelectMultipleControlValueAccessor for writing multi-select control values and listening to multi-select control changes. This happens irrespective of whether we bind [multiple] to true or false value.
SelectMultipleControlValueAccessor selector
So, the value bound to ngModel needs to be an array even when multiple is set to false. It works, but yes the model would be an array with one element.
Expecting the model to switch between an array and non-array type on basis of boolean value bound to [multiple], means that relevant ControlValueAccessor directives would need to be dynamically created and associated with same NgModel instance.
