错误TS2322:“事件”类型不可分配给“字符串”类型。[(ngModel)]="todoItem"(keyup)="addTodo()"

我正在尝试绑定我的输入以显示字符串。但我有这个错误:

错误: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  *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;
  }

回答

可能在 app.module.ts 中导入 FormsModule 可以解决这个问题。

import { FormsModule } from '@angular/forms';
...
imports: [
..,
FormsModule
],

保存并为项目服务。


回答

ngModel在 Forms 模块中定义,默认情况下不会导入,因此如果您想构建任何类型的表单或想要使用ngModel,您需要显式导入它。

app.Module.ts 中你需要这样做。

import { FormsModule } from '@angular/forms';
      imports: [
         FormsModule
      ]


以上是错误TS2322:“事件”类型不可分配给“字符串”类型。[(ngModel)]="todoItem"(keyup)="addTodo()"的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>