首页 > 解决方案 > 如何获取输入值并将其传递给角度组件?

问题描述

我是 Angular 新手,正在尝试创建一个简单的待办事项应用程序。

我使用 [(ngModel)] 将输入值传递给组件,但似乎我以不正确的方式进行操作。

这是我的代码

HTML:

<div class="todo-app">
  <h1>Todo List</h1>
  <div>
    <input type="text" class="input" placeholder="Enter your task" autofocus="" [(ngModel)]="value">
    <button class="btn" (click)="addTodo()">Add</button>
  </div>
</div>

ts:

import { Component } from '@angular/core';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.styl']
})

export class AppComponent {
  todos = [];
  id:number = 0;

  addTodo() {
    this.todos = [...this.todos, {title: this.value, id: this.id++, completed: false}];
    return this.todos;
  }

  removeTodo(id:number) {
   return this.todos.filter(todo => todo.id !== id)
  }

  toggleCompletionState(id:number) {
    this.todos.map(todo => todo.id === id ? {...todo, completed: !todo.completed} : todo)
  }

  getAllTodos() {
    return this.todos;
  }
}

这里有什么问题,为什么ngModel不起作用?

标签: angular

解决方案


在您的模板上,因为您在 ngModel 上分配了,所以也在您的 Component 上声明它以便能够在那里访问它的实例。

HTML

<input type="text" 
       class="input" 
       placeholder="Enter your task"
       [(ngModel)]="value">        // this 'value' must be instantiated on your component

零件

@Component({...}) {

   value: string;                  // Add this as you had used and assign it to your ngModel

   addTodo() {
      console.log(this.value);     // this will now have a value depends on your input from ngModel
   }

}

推荐阅读