Kaushik
Kaushik

Reputation: 114

Select does not render options on dynamic fetching of options

HTML:
<select (focus)="onFocus()">
    <option *ngFor="let c of myDropDown">{{c}}</option>
</select>
<input [hidden]="myDropDown !=='two'"type="text">

Component:
onFocus() {
    this.http.get('https://jsonplaceholder.typicode.com/posts').subscribe(val => {
      console.log(val)
      this.myDropDown = val;
    })
  }

On Focus of Select, I am trying to fetch the options by making a service call, but somehow the dropdown does not open and I have to click twice.

StackBlitz Link: https://stackblitz.com/edit/angular-select-example-3jvz1h?file=app%2Fapp.component.ts

Upvotes: 0

Views: 274

Answers (2)

Lowell Ed Llames
Lowell Ed Llames

Reputation: 207

Change your html to this:

<select (mouseover)="onFocus" (focus)="onFocus()">
   <option *ngFor="let c of myDropDown" [value]="c.id">{{c.title}}</option>
</select>

then add a hook using OnInit:

ngOnInit(){
  this.onFocus()
}

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222702

You dont have to generally use onFocus since you want to load initially you can put the service call inside the constructor and load the options as follows,

 constructor(private http: HttpClient) {
   this.http.get('https://jsonplaceholder.typicode.com/posts').subscribe(val => {
        this.myDropDown = val;
    });

 }

STACKBLITZ DEMO

Upvotes: 0

Related Questions