【问题标题】:Why do i see [object Object] inside my input?为什么我在输入中看到 [object Object]?
【发布时间】:2019-05-18 21:24:57
【问题描述】:

我不明白为什么在我的输入中看到的是[object Object],而不是占位符;

这是我的html

<div class="input-form">
  <input type="text" placeholder="Type name here..." [(ngModel)]="newItem">
  <button (click)="addItem()">Add new</button>
</div>
<ul>
  <li *ngFor="let item of items">{{ item }}
    <button (click)="deleteItem(item)" >Delete</button>
  </li>
</ul>

这里是 component.ts

newItem = {};
items = [];

addItem() {
  if (this.newItem !== null) {
    this.items.push(this.newItem);
    this.newItem = {};
  }
}

【问题讨论】:

  • 正如你所定义的newItem = {} 得到结果将其定义为newItem = '';
  • 如果你想把它作为一个对象保存,试试 json 管道:{{ item | json }}

标签: javascript angular typescript angular7


【解决方案1】:

[object Object]toString() 函数的结果。

const obj = { };
console.log(obj.toString());

结果:

[object Object]

您需要传递string 类型的值,但我强烈建议不要使用ngModel 传递值。您应该使用FormGroup 创建表单。

【讨论】:

  • FormGroup 绝对是要走的路,即使是非常简单的输入。我建议您习惯使用它,这样您就可以更好地编写快速表单。这是一个很棒的工具。
【解决方案2】:

您应该将newItem 定义为string,因为它引用了来自您的input elementbinding 目标值。 p>

newItem: string;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-24
    • 2015-07-03
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多