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

Angular页面默认展示数组首个元素问题求助

解决默认选中首个目的地的问题

你的代码问题出在两个关键点:

  • 组件初始化时destinations是空数组,selectedDestination = this.destinations[0]会得到undefined
  • 异步获取数据后,没有自动将第一个元素设为选中状态

修改你的getDestinations方法,在数据返回后直接设置选中第一个目的地:

export class DestinationComponent implements OnInit {
  destinations: Destinations[] = [];
  selectedDestination?: Destinations; // 用可选类型让代码更严谨

  constructor(private destinationsService: DestinationsService) {}

  getDestinations(): void {
    this.destinationsService
      .getDestinations()
      .subscribe((destinations) => {
        this.destinations = destinations;
        // 数据加载完成后,选中第一个元素(先判断数组非空)
        if (this.destinations.length > 0) {
          this.selectedDestination = this.destinations[0];
        }
      });
  }

  onSelect(destination: Destinations): void {
    this.selectedDestination = destination;
  }

  ngOnInit(): void {
    this.getDestinations();
  }
}

修改后,页面首次加载并获取到数据时,第一个目的地会自动被选中,对应的详情区域会正常显示,按钮的active样式也会自动生效。

内容的提问来源于stack exchange,提问作者Charles-Étienne

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 02:10:34