Angular5中mat-select组件*ngFor值绑定失效问题求助
Hey there, let's troubleshoot why your mat-select isn't showing the API data even though the console logs it. Looking at your code, I spot a few key issues that are likely causing this problem:
1. Critical Data Overwrite in Your Subscription
In your getNames() method, you first assign the valid API response to this.names, but immediately overwrite it with this.nameList—which doesn't seem to be defined anywhere! That's why the data disappears right after you fetch it.
Fixed Component Code:
// Declare and initialize variables in your component first names: any[] = []; nameselected: string; getNames(){ this.nameService.getNames().subscribe(data => { this.names = data; // Keep the API response assigned to 'names' console.log(this.names); // Fix: use 'this.names' instead of the undefined 'names' // Remove this line—it's overwriting your valid API data! // this.names=this.nameList; }); } // Call getNames() when the component initializes ngOnInit() { this.getNames(); }
2. Verify Data Structure Match
Double-check that the API response structure exactly matches what your HTML template expects. Your template assumes each item in names has:
- A
SurNameproperty (case-sensitive!) for the optgroup label - A
hobbiesarray containing objects withhobbyNameproperties
If the API returns keys like surname (lowercase 's') or hobby_name, your *ngFor won't find the data. Use the console log of this.names to confirm the structure matches.
3. Initialize Variables to Avoid Undefined Errors
By initializing names as an empty array (names: any[] = []), you prevent Angular from throwing errors while waiting for the API response. This ensures the *ngFor has something to iterate over immediately (even if it's empty at first).
Final Check for Your HTML
Your template looks correct as long as the data structure is right, but just to confirm:
<mat-select name="name" [(ngModel)]="nameselected"> <mat-optgroup *ngFor="let name of names" [label]="name.SurName"> <mat-option *ngFor="let hobby of name.hobbies" [value]="hobby.hobbyName"> {{ hobby.hobbyName }} </mat-option> </mat-optgroup> </mat-select>
After making these fixes, your mat-select should display the optgroups and options from the API response correctly!
内容的提问来源于stack exchange,提问作者vid

