Angular 如何获取输入值并将其传递给角度分量?
我对angular很陌生,正在尝试创建一个简单的todo应用程序 我使用[(ngModel)]将输入值传递给组件,但似乎我的方式不正确 这是我的密码 HTML:Angular 如何获取输入值并将其传递给角度分量?,angular,Angular,我对angular很陌生,正在尝试创建一个简单的todo应用程序 我使用[(ngModel)]将输入值传递给组件,但似乎我的方式不正确 这是我的密码 HTML: <div class="todo-app"> <h1>Todo List</h1> <div> <input type="text" class="input" placeholder="Enter your task" autofocus="" [(ngModel)
<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>
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不能工作?是因为
[(ngModel)]="someFieldInComponent"
组件中没有someFieldInComponent
(value
字段)
在您的模板上,因为您在ngModel上分配了值,所以也在组件上声明它,以便能够访问其实例
HTML
<input type="text"
class="input"
placeholder="Enter your task"
[(ngModel)]="value"> // this 'value' must be instantiated on your component
您忘记声明
值
字段。不过,这应该是可行的(不过,当您拥有多个值时,将单个值存储为属性有点奇怪)。无论如何,请详细说明你的问题是什么。我很困惑,我甚至不知道如何获取输入值并将其传递给组件以使用它,你能给我演示如何实现吗?我现在添加了字段,但没有任何效果!!,输入和按钮甚至没有显示在页面上也不知道为什么?准备好了吗stackblitz@Antoniossss即使不从typescript编译器的角度声明字段是无效的,它仍然会转换为有效的JS(因为您不必在JS中声明它)。所以问题必须在其他地方。我无法理解你,我在使用输入时遇到了一个问题,它消失了,不知道为什么?@Jeto我只看到这里有什么问题,为什么ngModel不工作,没有看到任何字段。
@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
}
}