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

Angular中push()后数组被重新初始化,新增元素丢失问题

问题:添加食材后页面重载,新数据丢失

父组件维护着一个食材数组,子组件输入新食材信息后点击按钮,数据能短暂出现在DOM中,但随即页面重载,数组恢复初始状态。

原因分析

子组件中的按钮设置了type="submit",如果这些输入控件被包裹在<form>标签内(即便代码里没显式写出,父组件模板可能隐含form结构),点击submit类型按钮会触发默认表单提交行为,导致整个页面刷新,组件重新初始化,之前添加的数据自然丢失。

解决方案

有两种简单的修复方式:

方式一:修改按钮类型

将按钮的type从submit改为button,彻底避免触发表单提交:

<button class="btn btn-success"
        type="button"
        (click)="onAddIngredient()">
    Add
</button>

方式二:阻止默认事件

如果需要保留submit类型(比如配合表单验证),可以在点击事件中传入事件对象并阻止默认行为:

  1. 子组件模板修改:
<button class="btn btn-success"
        type="submit"
        (click)="onAddIngredient($event)">
    Add
</button>
  1. 子组件TS代码修改:
onAddIngredient(event: Event) {
    event.preventDefault(); // 阻止默认表单提交行为
    const ingName = this.nameInputRef.nativeElement.value;
    const ingAmount = this.amountInputRef.nativeElement.value;
    const newIngredient = new Ingredient(ingName, ingAmount);
    this.ingredientAdded.emit(newIngredient);
    // 可选:清空输入框,提升体验
    this.nameInputRef.nativeElement.value = '';
    this.amountInputRef.nativeElement.value = '';
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 19:20:18