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

Angular项目往数组添加元素后如何清空输入框内容

方案1:最小改动,复用现有模板引用变量

你现在代码里已经给input加了模板引用变量#item,只需要做2处修改即可实现需求:

  1. 修改HTML中按钮的点击事件,把整个input元素而非仅输入值传入create方法:
<button type="submit" class="btn btn-success" (click)="create(item)" style="width: 80px;">Add</button>
  1. 修改TS中的create方法,添加完数据后清空input的value属性:
create(inputEl: HTMLInputElement) {
  // 可添加非空校验避免提交空值
  if (!inputEl.value.trim()) return
  this.collection.push({
    name: inputEl.value
  });
  // 直接清空输入框原生值
  inputEl.value = ''
}

方案2:双向绑定实现(更符合Angular开发规范,推荐)

用Angular内置的ngModel双向绑定管理输入值,更适合后续功能扩展:

  1. 先在app.module.ts中导入表单模块:
import { FormsModule } from '@angular/forms';
// 后续把FormsModule添加到@NgModule的imports数组中即可
  1. 修改HTML的input元素,添加双向绑定声明:
<input type="text" class="form-control" name="Value" id="Value" [(ngModel)]="newItemName">
  1. 修改TS逻辑:
export class AppComponent {
  collection: any = [];
  // 声明和输入框绑定的变量
  newItemName: string = '';

  create() {
    if (!this.newItemName.trim()) return
    this.collection.push({
      name: this.newItemName
    });
    // 清空绑定变量即可同步清空输入框
    this.newItemName = ''
  }
}

额外逻辑修正

你当前的删除功能存在bug:deleteItem方法现在传入的是数组元素对象,而splice第一个参数需要接收元素下标才能正常删除,修改方法如下:

  1. 修改ngFor语句获取元素索引:
<tr *ngFor="let item of collection; let i = index">
  1. 修改删除按钮传参:
<button (click)="deleteItem(i)" class="btn btn-danger btn-sm">Delete</button>
  1. 修改TS删除逻辑:
deleteItem(index: number) {
  this.collection.splice(index, 1);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 23:15:07