Select在动态获取选项时不呈现选项

时间:2018-10-23 01:59:11

标签: angular angular-changedetection

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

2 个答案:

答案 0 :(得分:0)

您通常不必使用onFocus,因为您要首先加载,您可以将服务调用放入构造函数中并按如下所示加载选项,

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

 }

STACKBLITZ DEMO

答案 1 :(得分:0)

将您的html更改为此:

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

然后使用OnInit添加一个钩子:

ngOnInit(){
  this.onFocus()
}