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

Angular中不使用模板/响应式表单如何控制台输出多个输入值

Angular 无表单场景多输入框值提交打印方案

问题原因

你当前代码中两个输入框使用了完全相同的模板引用变量名#input,Angular 只会识别最后一个同名的模板引用,因此提交时只能拿到单个输入框的值。

固定数量输入框最简实现

不需要引入任何表单模块,只需要给每个输入框设置唯一的模板引用变量名,提交时把所有输入框的值一起传入点击方法即可。

修改后的模板代码

<!-- 两个输入框分别设置不同的模板引用名 -->
<input class="form-control" placeholder="Text" #firstInput>
<input class="form-control" placeholder="Text" #secondInput>
    
<div class="button" (click)="onClick(firstInput.value, secondInput.value)">
   <button class='btn btn-dark'>Submit</button>
</div>

修改后的TS代码

onClick(firstVal: string, secondVal: string) {
  // 直接打印所有传入的值,也可以组装为对象/数组输出
  console.log('输入框1值:', firstVal);
  console.log('输入框2值:', secondVal);
  // 组装为结构化对象打印更清晰
  console.log('全部输入值:', {
    firstInput: firstVal,
    secondInput: secondVal
  });
}

扩展:多输入框/动态输入框实现

如果输入框数量较多、或是后续会动态增减输入项,逐个传参维护成本高,可以通过容器遍历的方式统一收集值,同样不需要表单支持:

模板代码

<!-- 给所有输入框加统一外层容器,定义模板引用 -->
<div #inputWrap>
  <input class="form-control collect-input" placeholder="Text">
  <input class="form-control collect-input" placeholder="Text">
  <input class="form-control collect-input" placeholder="Text">
  <!-- 可随意增减输入框,无需修改点击事件传参 -->
</div>

<div class="button" (click)="onClick(inputWrap)">
   <button class='btn btn-dark'>Submit</button>
</div>

TS代码

onClick(wrapEl: HTMLElement) {
  // 遍历容器内所有目标输入框,收集值生成数组
  const allInputValues = Array.from(
    wrapEl.querySelectorAll<HTMLInputElement>('.collect-input')
  ).map(item => item.value);
  console.log('所有输入框值:', allInputValues);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 11:01:06