【问题标题】:i don't get to see the two way binding value after the first submit button click第一次提交按钮单击后,我看不到双向绑定值
【发布时间】:2018-10-21 00:33:25
【问题描述】:

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

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

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

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;
 }

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

【问题讨论】:

  • 因为您在 addItem 函数中将 this.test 的值重置为空字符串
  • 就像我猜的一样。我希望在收集值后清除输入字段。请问我该怎么做。谢谢

标签: javascript angular typescript


【解决方案1】:

在你的 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多