0
votes

I am using [(ngModel)] top bind various inputs and select elements in my angular application. I also use a service with ngModel. When using the select element, my app is showing an empty option.

Even if I change the value of the first option to something other than an empty string, the same issue comes up.

<div>
  <input 
    placeholder="Ohio Volume"
    type="number"
    class="text-input"
    value="{{ this.inputsService.ohioVolume }}"
    [(ngModel)]="ohioVolume"
    (change)="this.inputsService.setOhioVolume(ohioVolume)"
  >
</div>
<div>
  <select
    class="select" 
    value="{{ this.inputsService.ohioReporter }}"
    [(ngModel)]="ohioReporter"
    (change)="this.inputsService.setOhioReporter(ohioReporter)">
    <option value="">Ohio Reporter</option>
    <option value="Ohio St.3d">Ohio St.3d</option>
    <option value="Ohio St.2d">Ohio St.2d</option>
    <option value="Ohio St.">Ohio St.</option>
  </select>
</div>

My inputsService typescript file shows in relevant part:

ohioReporter: string

setOhioReporter(ohioReporter) {
    this.ohioReporter = ohioReporter
}

The input code is working appropriately, but the select shows an empty box regardless of the value of the first option. I would prefer the solution to remain only in the html code and not require any typescript code.

2
Do you have value on this [(ngModel)]="ohioReporter"? if not, that's why it shows empty. - Maihan Nijat
could you maybe show the ts file? - Miaan

2 Answers

0
votes

Try with this in your ts/Service, maybe its because its not defined by default

   ohioReporter: string = ""
0
votes

you need to modify yout code in this way:

 <select
    class="select" 
    value="{{ this.inputsService.ohioReporter }}"
formControlName="name" [ngModel]="ohioReporter" name="ohioReporter" (ngModelChange)="ohioReporter($event)">
    <option value="">Ohio Reporter</option>
    <option value="Ohio St.3d">Ohio St.3d</option>
    <option value="Ohio St.2d">Ohio St.2d</option>
    <option value="Ohio St.">Ohio St.</option>
  </select>

the .ts becames:

@Output() ohioReporter: number;

....
  ohioReporter(ohioReporter) {

    this.ohioReporter= ohioReporter;
}