首页 > 解决方案 > 第一次提交按钮单击后,我看不到双向绑定值

问题描述

我正在尝试将输入中的项目添加到 div 中id = items

它似乎在第一次提交点击时有效,但之后失败。

我观察到在第一次提交点击后,双向数据绑定似乎消失了。

HTML 代码:

    <form>
        <input type="text"name="item"
        [(ngModel)]="test.text"> 
        <br> 
        <p>{{test.text}}</p> <!--disappears after the first 
        button click-->

        <input type="submit" value="Add" 
        (click)="addItem()">
    </form>
    <div id="items" *ngFor="let goal of goals">
        <p>
          {{ goal.text }}
        </p>
        <p>
          {{ goal.num }}
        </p>

    </div>

在我的组件文件中,我试图将用户输入推送到一个数组中并使用ngFor上面的语法循环它,但它在第一个结果后返回空。

goals = [];
test: any = {text: "ok", num: "789"};

addItem() {
    this.goals.push(this.test);
    this.test = '';
    this.itemCount = this.goals.length;
 }

我哪里会出错?提前致谢。

标签: javascriptangulartypescript

解决方案


在您的 addItem 函数中只需更改此

addItem() {
 this.goals.push(this.test);
 this.test = '';
 this.itemCount = this.goals.length;
}

addItem() {
 this.goals.push({...this.test});
 this.test.text = '';
 this.itemCount = this.goals.length;
}

推荐阅读