use*_*224 6 types typescript angular
我正在尝试绑定我的输入以显示字符串。但我有这个错误:
错误:list.component.html:3:15 - 错误 TS2322:“事件”类型不可分配给“字符串”类型。.
3 [(ngModel)]="todoItem" ~~~~~~~~~ 4 (keyup) ="addTodo()"
src/app/components/todo-list/todo-list.component.ts:5:16
5 templateUrl: './todo-list.component.html',
todo-list.componentn.html :
<input type="text"
placeholder="What needs to be done"
[(ngModel)]="todoItem"
/>
<div class="item-left" *ngFor="let todo of todos">
<input type='checkbox' >
<p>{{todo.title}}</p>
</div>
todo-list.component.ts:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-todo-list',
templateUrl: './todo-list.component.html',
styleUrls: ['./todo-list.component.css'],
})
export class TodoListComponent implements OnInit {
todos!: Todos[];
todoItem!: string;
constructor() {}
ngOnInit(): void {
this.todoItem = '';
this.todos = [
{
id: 1,
title: 'Surya',
},
];
}
}
//interface to help with type error
interface Todos {
id: number;
title: string;
}
Run Code Online (Sandbox Code Playgroud)
小智 21
可能在 app.module.ts 中导入 FormsModule 可以解决这个问题。
import { FormsModule } from '@angular/forms';
...
imports: [
..,
FormsModule
],
Run Code Online (Sandbox Code Playgroud)
保存并为项目服务。
小智 11
我也面临这个问题。我已经在app.module中导入了FormsModule。即使在那之后,我收到错误“无法绑定 ngModel,它不是输入的已知属性”。我很困惑并花了很多时间在这上面。幸运的是,我发现我没有在 app.module 中导入该组件。我仅使用 CLI 来生成组件。但我不知道为什么它没有添加到应用程序模块。通常情况下,确实如此。
因此,如果您遇到此问题,值得在 app.module 中检查一次该组件是否已添加到声明数组中。
添加声明数组,解决了我的问题。
小智 10
ngModel在 Forms 模块中定义,默认情况下不会导入,因此如果您想构建任何类型的表单或想要使用ngModel,您需要显式导入它。
在app.Module.ts 中你需要这样做。
import { FormsModule } from '@angular/forms';
imports: [
FormsModule
]
Run Code Online (Sandbox Code Playgroud)
小智 10
我正在使用自定义模块。所以对我来说我补充道:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { MyComponent } from './mycomponent.component'
import { SomeOtherComponent } from './components/someother.component'
@NgModule({
declarations: [
MyComponent,
SomeOtherComponent
],
imports: [
CommonModule,
RealtorToolsRoutingModule,
FormsModule
]
})
export class MyModule{ }
Run Code Online (Sandbox Code Playgroud)
我在父Module中添加了Forms模块,子组件继承了FormsModule。
这是将 FormsModule 添加到 app.module.ts 的替代方法
您需要将 FormsModule 添加到 app.module.ts 中的导入字段
import { FormsModule } from '@angular/forms'
imports: [FormsModule],
| 归档时间: |
|
| 查看次数: |
9261 次 |
| 最近记录: |