2

I am new to angular. I am having trouble understanding the functionality of mat-select and mat-option elements.

I want my mat-select to fetch the data ONLY when clicked. But right now I have to click twice in order to make the list appear and I really don't understand why. If anyone has any idea I would be grateful.

My HTML:

<mat-select placeholder="Aircraft Family" [(ngModel)]="aircraftFamily" (click)="loadFamilies()">
    <mat-option *ngFor="let myAircraftFamily of aircraftFamilies" [value]="myAircraftFamily.name">{{myAircraftFamily.name}}</mat-option>
</mat-select>

My Module:

@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})

export class HeaderComponent implements OnInit {

   aircraftFamily: string = '';
   aircraftFamilies = [];

   constructor(private route: ActivatedRoute, private headerService: HeaderService) {
       this.route.paramMap.subscribe(
           (params: ParamMap) => {
               if (params.has('family')) {
                   this.aircraftFamily = params.get('family');
               }
           }
       );
   }

   ngOnInit() {
   }

   loadFamilies() {
       this.headerService.getAircraftFamilies().then((result) => {
           this.aircraftFamilies = result; // [{id:xxx, name:aircraftX},..]
       }, (error: HttpErrorResponse) => {
           console.log('error: ' + error)
       });
   }
}
Nadun Kulatunge
  • 1,567
  • 2
  • 20
  • 28
lolplayer101
  • 2,112
  • 2
  • 17
  • 26
  • duplicate: https://stackoverflow.com/questions/47020988/angular-material-md-select-load-options-in-async-way/ – Curtis May 01 '18 at 16:11

1 Answers1

4

I think the issue is that the click event to open the select is getting fired before the async method can load the options into the dom. So the select doesn't open because it has no options.

The way I got around this was to add a disabled option to the select that shows up if there are no options in my option list. This option contains a span and a spinner to indicate it is loading.

Here is a stackblitz example demonstrating this.

Note: In my example, the service can return different data depending on the circumstances. 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.

Curtis
  • 3,170
  • 7
  • 28
  • 44