如何获取输入值并将其传递给角度分量?

Sah*_*ndy 3 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>
Run Code Online (Sandbox Code Playgroud)

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

这里出了什么问题以及为什么ngModel不起作用?

KSh*_*ger 5

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

超文本标记语言

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

成分

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

}
Run Code Online (Sandbox Code Playgroud)