Search code examples
htmlangular6componentshtml-selectngmodel

Strange behavior of <select> component with ngModel


I'm developing a web application using Angular 6. if I create a custom component that simulates the HTML <select>, I can not make it have a default value when it is referenced by another component! You can find the (simple) application code at the following link: stackblitz here

In this question I asked how to set a default value when the ngModel is present ( the selected attribute of <option> doesn't work anymore!). As you can see my input-select custom component initialize value (value linked to the ngModel).

value: any = 'default';

Unfortunately, however, the component is displayed like this:

enter image description here

As you can see the console, at the press of submit, print this:

enter image description here

I would like this situation not to show up: I would like a combo box with a pre-selected value. I can't understand what I was wrong with this application.


Solution

  • You had used ngModel but did not bind with anything so Angular doesn't know what value it supposed to bind with. You should bind ngModel with property which contains the default value.

    <form #form="ngForm" (ngSubmit)="onSubmit(form.value)">
      <input-select
      name="name"
      [options]="my_options"
      [(ngModel)]="value"
      ></input-select>
    
      <input type="submit" value="Submit"/>
    </form>
    

    Working copy is here - https://stackblitz.com/edit/angular-qanpuu