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

如何在Angular中点击按钮将输入的经纬度坐标添加到列表

实现方案

你可以按照以下两步修改代码完成需求:

1. 修改组件的.ts文件

添加航点存储数组和点击触发的添加方法:

// 组件类内新增代码
// 存储所有航点的数组
waypoints: {lat: string | number, lon: string | number}[] = [];

// 添加航点的方法
addWaypoint() {
  // 校验经纬度输入不为空
  if (this.latValue?.trim() && this.lonValue?.trim()) {
    // 将输入的坐标加入数组
    this.waypoints.push({
      lat: this.latValue,
      lon: this.lonValue
    });
    // 清空输入框方便下次输入
    this.latValue = '';
    this.lonValue = '';
  }
}

2. 修改HTML模板

需要调整两处代码:

  • 给Add Waypoint按钮绑定点击事件,修改为:
<button mat-button color="primary" (click)="addWaypoint()">Add Waypoint</button>
  • 调整航点列表部分,使用*ngFor循环渲染所有已添加的航点,替换原有写死的列表项:
<mat-list>
    <div mat-subheader>Waypoints</div>
    <mat-list-item *ngFor="let point of waypoints; let i = index">
        <mat-icon mat-list-icon>place</mat-icon>
        <div mat-line>Waypoint {{i + 1}}</div>
        <div mat-line>{{point.lat}}, {{point.lon}}</div>
    </mat-list-item>
</mat-list>

修改完成后,输入经纬度点击按钮即可自动在列表中新增对应的航点信息。

内容的提问来源于stack exchange,提问作者Brandon Pyle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 10:48:04