代码之家  ›  专栏  ›  技术社区  ›  Ashy Ashcsi

angular6:将输入字段的值传递给组件

  •  2
  • Ashy Ashcsi  · 技术社区  · 6 年前

    我试图将输入字段的值传递给组件类。但它似乎不起作用。请查找以下代码:

    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>
    

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

    但点击按钮会出现以下错误:

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

    我使用角度材质框架来渲染元素。有人能告诉我我做错了什么吗?

    谢谢

    3 回复  |  直到 6 年前
        1
  •  9
  •   Artem Arkhipov user1682140    6 年前

    尝试添加 #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>
    
        2
  •  -1
  •   Kelvin Santiago    6 年前

    在元素中使用#todo:

    <input matInput type="text" name="todo" #todo placeholder="Enter a todo">
    

    使用方法:

    {{ todo.value }}
    
        3
  •  -1
  •   bgraham    6 年前

    我认为更容易使用的另一种方法是有一个支持字段并绑定到它:

    html格式:

    <mat-card>   
      <form>
        <mat-form-field class="example-full-width">
          <input [(ngModel)]="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()">Add Todo
        </button>   
      </form> 
    </mat-card>
    

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

    这样做更容易验证他们输入的值,并在成功提交后将字段重置为空。