Angular 2 add new item from input

Im new for Angular2 and Im trying to add a new item to the list from the input. But then click to send me instead of the text [object Object].

Here is my code:

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

all-players.ts

export let Players: Player[] = [
];

thanks for answers

+4
source share
1 answer

I will write a complete answer.

In your component (TS file):

items = Players;
name;

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

In your 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>

My guess is that you submit your form 2 times.

0
source

Source: https://habr.com/ru/post/1680327/


All Articles