Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular6: passing value of the input field to the component

I am trying to pass value of the input field to the component class. But it does not seem to be working. Please find the code below:

todoinput.component.html

<mat-card>
  <form>
    <mat-form-field class="example-full-width">
      <input matInput type="text" name="todo" placeholder="Enter a todo">
    </mat-form-field>
    &nbsp; &nbsp;
    <button mat-raised-button color="primary" type="button" (click)="addTodo(todo.value)">Add Todo
    </button>
  </form>
</mat-card>

todoinput.component.ts

  addTodo(text) {
    this._todosService.addTodo({
      text: text,
    }).subscribe((todo) => {
      return this.newTodo.emit(todo);
    })
  }

But clicking on the button throws the error below:

ERROR TypeError: Cannot read property 'value' of undefined
    at Object.eval [as handleEvent] (TodoinputComponent.html:7)
    at handleEvent (core.js:10258)

I am using angular material framework for rendering the elements. Could anyone let me know what am I doing wrong here ?

Thanks

like image 462
Ashy Ashcsi Avatar asked Sep 05 '18 17:09

Ashy Ashcsi


1 Answers

Try to add #todo to the input. After that angular should be able to acces to the right input. Without that it gets undefined variable instead.

<mat-card>
  <form>
    <mat-form-field class="example-full-width">
      <input #todo matInput type="text" name="todo" placeholder="Enter a todo">
    </mat-form-field>
    &nbsp; &nbsp;
    <button mat-raised-button color="primary" type="button" (click)="addTodo(todo.value)">Add Todo
    </button>
  </form>
</mat-card>
like image 93
Artem Arkhipov Avatar answered Sep 23 '22 13:09

Artem Arkhipov