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
相关产品推荐
相关产品推荐

