Angular Material md-select load options in async way

元气小坏坏 提交于 2019-12-24 06:13:15

问题


I need to load select's options asynchronously ( through a service), using the Angular Material md-select component.

Actually, I use a click event to load data. It works but I need to click the select twice to show the options. That it's a problem.

The expected behavior is shown at this link (AngularJs Material)

The actual behavior is shown at this link.

Is Async options' loading supported by md-select?


回答1:


The reason you need to click twice is because when you first click, there are no options in the select control and so it doesn't try and open the panel. Then your async method loads the options into the DOM and on the next click it will open.

In order to deal with this, you must always include at least one <mat-option> in your <mat-select>. You can add a disabled <mat-option> with a <mat-spinner> showing that the data is loading for example.

Here the most simple example of that. This is not the best approach... see below.

However, this still uses the click event which isn't the best approach. If you put the click event on the <mat-select> there are spots where you can click on the control but your click event wont trigger even though the dropdown panel still opens (places like the floating label area). You could put the click event on the <mat-form-field> but then there will be places where you can click and trigger the click event but the dropdown panel wont open (places like the hint/error text area). In both cases you lose keyboard support.

I would suggest using the <mat-select> openChanged event instead of a click event. This has its own quirks too but they are manageable.

Here is an example using the openChanged event. I also made the component more robust overall.

I also made a version that uses the placeholder element to show the spinner instead of using a disabled mat-option. This required View Encapsulation to be turned off.

Note: In my example, the service can return different data depending on the circumstances. To simulate this my fake service keeps track of how many requests you send it and changes the options returned accordingly. So I have to set the option list back to empty and clear the formControl's value every time the list is opened. I save the selected value before clearing the formControl so that if the service returns a list with the same item I can automatically reselect the value. If you only need to load the options once, then you would want to modify the code a bit to only load the options the first time the user opens the select.



来源:https://stackoverflow.com/questions/47020988/angular-material-md-select-load-options-in-async-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!