【问题标题】:Angular 11 Can't bind to ngModelAngular 11 无法绑定到 ngModel
【发布时间】:2021-06-24 18:02:51
【问题描述】:

在用Angular 11 编写的应用程序中,我在html 文件中有输入和two way binding:

<input type="text" class="" id="inputName"   required minlength="3" [(ngModel)]="postModel.name">

在 ts 文件中我有:

@Component({
  selector: 'app-home',
  templateUrl: './add-client.component.html',
})
export class AddClientComponent implements OnInit {

  public postModel: any = {};
  public clientDTO: ClientDTO;
  public resultMessage: string;

  constructor(private route: ActivatedRoute, private router: Router, private clientService: ClientService) {
    this.postModel.name = '';
    this.resultMessage = '';

在app module:

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

imports: [
    FormsModule,
    ReactiveFormsModule,

绑定two-way 不起作用。当我在 html 中输入文本时 postModel.name 仍然是空的。当我在 html 中添加 {{ postModel.name }} 并在输入中输入文本时,值不会显示。

在控制台我有错误:

Compiled successfully.

    Error: src/app/add-client/add-client.component.html:5:73 - error NG8002: Can't bind to 'ngModel' since it isn't a known property of 'input'.

    5       <input type="text" class="" id="inputName" required minlength="3" [(ngModel)]="postModel.name" style="background-color:white;">
                                                                              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

      src/app/add-client/add-client.component.ts:11:16
        11   templateUrl: './add-client.component.html',
                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        Error occurs in the template of component AddClientComponent.

但有时没有错误但绑定不起作用。 我有Angular 11

【问题讨论】:

  • AddClientComponent 是在应用模块中,还是在另一个模块中?
  • 你说得对,declarations 部分的应用模块中缺少AddClientComponent

标签: angular data-binding angular-ngmodel


【解决方案1】:

你是对的,在声明部分的应用模块中缺少 AddClientComponent

【讨论】:

    猜你喜欢
    • 2017-12-06
    • 2023-03-16
    • 2019-10-12
    • 1970-01-01
    • 2017-02-10
    • 2020-09-12
    • 2019-11-05
    • 2021-05-23
    • 2018-12-05
    相关资源
    最近更新 更多