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

Angular选中卡片时如何更新输入框值并调用postToken提交数据

实现需求

选中页面内某张卡片时,表单输入框自动读取JSON对象里的对应数据完成填充,效果参考下图:
卡片选中自动填充表单示例


现有数据结构

接口返回的JSON数据结构如下,返回值会存储在responseData变量中:

{
  "status": true,
  "data": [
    {
      "id": 1,
      "pessoa_id": 75505,
      "created_at": "2022-02-01T17: 42: 46.000000Z",
      "holder": "LEONARDO LIMA",
      "validade": "2026-06-01",
      "bandeira": "Mastercard"
    }
  ]
}

现有代码逻辑

获取接口数据的方法

renderTokenCard() {
  this.mundipaggS.checkToken().subscribe((response: any) => {
    console.log(JSON.stringify(response));
    this.cartS.tokenCard = response;
    this.responseData = response;
    console.log(JSON.parse(JSON.stringify(response)));
  });
}

卡片选中触发的方法

SelecionarCartao() {
  this.mundipaggS.postToken(this.responseData)
  console.log(this.responseData)
}

现有表单HTML代码

<div class="form-group ">
  <label for="ncartao">Número do cartão <span class="text-danger"> *</span></label>
  <input name="card-number" maxlength="19" #cardNumber formControlName="digiNumero" id="ncartao" type="text"
    class="form-control col-lg-6  ">
</div>

<div class="form-group">
  <label for="nomeimpresso">Nome <b>impresso</b> no cartão<span class="text-danger"> *</span></label>
  <input #nomeImpresso formControlName="digiNome" name="holder-name" id="nomeimpresso" class="form-control col-lg-6"
    type="text">
</div>

待实现目标

  • 正确获取responseData中选中卡片的对应值,传入postToken方法完成接口提交
  • 选中卡片时,将对应卡片的字段数据自动填充到绑定的表单输入框中

实现方案

1. 给卡片列表加选中传参

你现在渲染卡片列表的时候,肯定是循环responseData.data生成DOM,直接给每个卡片项加点击事件,把当前循环到的单条卡片数据传进去就行,别直接拿整个responseData操作——这是个数组,不定位到单条的话根本不知道用户点的是哪张。
模板改法参考:

<!-- 卡片列表循环区域,根据你自己的实际类名调整 -->
<div class="card-list">
  <div 
    class="card-item" 
    *ngFor="let card of responseData?.data" 
    (click)="SelecionarCartao(card)"
  >
    <!-- 你原来的卡片展示内容,比如持卡人、有效期、卡组织 -->
    <span>{{card.holder}}</span>
    <span>{{card.bandeira}} | {{card.validade | date:'MM/yy'}}</span>
  </div>
</div>

2. 改造选中方法,同时完成表单赋值和接口提交

看你表单用的是Angular响应式表单(有formControlName标识),直接用patchValue给控件赋值就行,接口提交也只传选中的单条卡片数据,别传整个接口返回的大对象:

// 注意替换你自己的表单组变量名,这里假设表单组名叫paymentForm
SelecionarCartao(selectedCard: any) {
  // 填充表单,字段和你写的formControlName一一对应
  this.paymentForm.patchValue({
    digiNome: selectedCard.holder,
    // 你现在贴的示例JSON里没有卡号字段,等接口返回卡号后把key替换成对应字段就行
    digiNumero: selectedCard.card_number ?? ''
  });

  // 提交接口,传选中的卡片数据
  this.mundipaggS.postToken(selectedCard).subscribe({
    next: (res) => console.log('令牌提交成功', res),
    error: (err) => console.error('提交失败', err)
  });
}

踩坑提醒

  • 所有依赖checkToken接口返回值的逻辑,必须写在subscribe回调里,别在外面直接拿this.responseData用,异步请求没返回的时候这个变量是空的
  • 如果你的表单是模板驱动表单,直接给绑定的ngModel对应变量赋值就行,逻辑完全一致
  • 现在示例返回的卡片数据里缺少卡号字段,要填充卡号输入框的话先和后端确认返回字段名,别硬写

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.15 16:15:59