-->

Angular Material md-select load options in async w

2019-07-24 17:26发布

问题:

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>. Making this a disabled <mat-option> with a <mat-spinner> showing that the data is loading seems to be a good start.

Here the most simple example of that. Not the best approach explained 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 and the click event wont trigger but the dropdown panel will still open (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 not actually open the dropdown panel (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 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. If you only need to load the options once, then you would have to modify the code a bit to block reloading the options every time the user opens the select.

The more robust versions save the selected value between loads and reselects the value if it is still in the list.