0
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;
    })
  }

在选择焦点上,我试图通过拨打服务电话来获取选项,但不知何故下拉菜单没有打开,我必须点击两次。

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

4

2 回答 2

0

您不必通常使用 onFocus ,因为您想最初加载您可以将服务调用放在构造函数中并加载选项,如下所示,

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

 }

堆栈闪电战演示

于 2018-10-23T02:05:37.950 回答
0

将您的 html 更改为:

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

然后使用添加一个钩子OnInit

ngOnInit(){
  this.onFocus()
}
于 2018-10-23T02:05:42.507 回答