首页 > 解决方案 > 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

标签: angularparameter-passingangular6

解决方案


尝试添加#todo到输入。之后,角度应该能够访问正确的输入。没有它,它会得到未定义的变量。

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

推荐阅读