angular - 如何获取输入值并将其传递给角度组件?
问题描述
我是 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不起作用?
解决方案
在您的模板上,因为您在 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
}
}
推荐阅读
- c++ - 使用 IDA Pro 和 IDAPython 获取 CPP 对象的值
- regex - Htaccess 将非 www 重写为 www /and/ domain.tld/id 到 domaine.tld/page.php?id=
- flutter - 如何重建从 Flutter 中的函数构建的小部件?
- weather-api - React> locale img 而不是来自 api 的图像
- android - 错误:在内核映像文件中找不到“Linux 版本”字符串:D:\Android\androidSDK/system-images\android-30\google_apis\x86_64\/kernel-ranchu
- node.js - 如何在nodejs后端验证谷歌登录(通过Firebase)idToken?
- python - 部分离散的颜色图 matplotlib
- arrays - 如何使用bash替换文件中的数组?
- android - 提交现有 android app/apk 的新版本会受到 Android App Bundle 要求的影响吗?
- r - 从 rpart 模型中检索决策规则