1

I'm having a really strange issue with Angular forms.
So basically, I have a form that includes a custom select with 3 options.
<div class="form-group"> <label class="form-label" for="custom-select">Type of Map:</label> <select class="custom-select" ngModel #mapType="ngModel" name="mapType" required> <option *ngFor="let m of mapTypes" value="{{m.value}}">{{m.name}}</option> </select> </div>

Now, in theory this should load the data from this array:

mapTypes = [{value:1, name:'Draw All'}, {value:2, name: 'Draw Movements (Display Most Recent)'}, {value:3, name: 'Draw Movements (Display All)'}];

And it successfully does. The only problem is on page load it looks like this:
dropdownOnLoad

But, when I click on it I get all of the options (and the values do successfully pass when the form is submitted)
dropdownWhenClicked

So, my question is, why is this happening and how can I fix it? The options are loading in correctly and the first option is selected as default (which is what I want). Yet it won't show written into the box when the page is loaded. It's weird because I have another dropdown that works just like this (actually more extensive) and it works perfectly fine.

AZ1997
  • 43
  • 6

2 Answers2

1

I would suggest to bind the ngModel to a local variable and init this with your desired value.

[(ngModel)]="selected"

E.g.:

HTML:

<div class="form-group">
   <label class="form-label" for="custom-select">Type of Map:</label>
       <select class="custom-select" [(ngModel)]="selected" name="mapType" required >
           <option *ngFor="let m of mapTypes" value="{{m.value}}" >{{m.name}}</option>
       </select>
 </div>

Component:

  mapTypes = [{value:1, name:'Draw All', selected: true}, {value:2, name: 'Draw Movements (Display Most Recent)'}, {value:3, name: 'Draw Movements (Display All)'}];

  selected = this.mapTypes[0].value;

Working Stackblitz

Note: General it is a good idea/ easier to use the material components with Angular or try ngx-bootstrap if your prefer bootstrap.

zerocewl
  • 11,401
  • 6
  • 27
  • 53
0

The problem might be that you are not initializing the value of mapType, that is why it does no show anything and it change when you click. So try to set the initialize mapType for example onInit method.

cabesuon
  • 4,860
  • 2
  • 15
  • 24