Angular 2从输入

时间:2017-06-28 14:25:31

标签: javascript angular typescript input

我是Angular2的新手,我试图从输入中添加一个新项目到列表中。但是然后点击提交我而不是文本[object Object]。

这是我的代码:

app.component.html

<form (submit)="addItem(item)">
    <md-input-container>
      <input [(ngModel)]="name" mdInput placeholder="add" name="addNew">
    </md-input-container>
      <button type="submit" md-icon-button>
          <i class="material-icons">send</i>
    </button>
    </form>

app.component.ts

items = Players;
 name;

 addItem(name): void {
        this.items.push(new Player({
            name : name
        }));
    }

player.ts

export class Player {
    id: number;
    name: string;
    count: number;

    constructor(name){
        this.id;
        this.name = name;
        this.count = 0;
    }

全players.ts

export let Players: Player[] = [
];

感谢您的回答

1 个答案:

答案 0 :(得分:0)

我会写一个完整的答案。

在您的组件(TS文件)中:

items = Players;
name;

addItem() { this.items.push(new Player({ name : this.name })); }

在您的HTML中:

<form (submit)="addItem()" novalidate>
    <md-input-container>
        <input [(ngModel)]="name" mdInput placeholder="add" name="addNew">
    </md-input-container>
    <button type="submit" md-icon-button>
        <i class="material-icons">send</i>
    </button>
</form>

我的猜测是你提交表格2次。