You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular5中mat-select组件*ngFor值绑定失效问题求助

Fixing mat-select *ngFor Data Binding Issue in Angular 5

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 SurName property (case-sensitive!) for the optgroup label
  • A hobbies array containing objects with hobbyName properties

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:53:56