【问题标题】:Can't bind to ngModel even though I'm importing FormsModule & syntax appears correct即使我正在导入 FormsModule 也无法绑定到 ngModel 并且语法似乎正确
【发布时间】:2021-06-22 10:36:03
【问题描述】:

我的问题始于我在 Spring Boot 和 Angular 中进行的应用程序练习。我发现我无法绑定到 ngModel、ngClass 和其他一些东西。因此,我一直在努力学习基础知识,并尝试了《Angular Development with TypeScript, 2nd Ed》一书中的简单练习。当我无法摆脱错误时,我从 GitHub 复制了本书的代码,但仍然得到错误。代码如下:

app.module.ts

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule
  ],
  declarations: [
    AppComponent
  ],
  bootstrap: [
    AppComponent
  ]
})
export class AppModule {}

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <input type="text"
        placeholder="Enter shipping address"
        [(ngModel)]="shippingAddress">
    <button (click)="shippingAddress='123 Main Street'">Set 
    Default Address</button>
    <p>The shipping address is {{ shippingAddress }}</p>
  `
})
export class AppComponent {
  shippingAddress: string;
}

如您所见,FormsModule 已导入,[(ngModel)] 的语法是正确的,但 VS Code 仍然显示错误“无法绑定到 ngModel,因为它不是输入的已知属性。 "

我希望,如果你们都可以帮助我解决这里的问题,那么答案将适用于我正在进行的 Spring Boot/Angular 练习。

【问题讨论】:

    标签: angular binding ngmodel two-way-binding


    【解决方案1】:

    这可能是 VS 代码的问题。有时关闭 VSCode 并再次打开有助于解决这些问题。

    我在 stackblitz 上尝试了相同的示例,它对我有用 https://stackblitz.com/edit/angular-vaeac1?file=src/app/app.component.ts

    【讨论】:

    • 关闭和打开没有帮助,但您的建议也促使我查看 VS Code 中的其他内容。我禁用了我添加的 Angular 语言服务扩展,瞧!错误消失了。谢谢!
    【解决方案2】:

    尝试为输入提供名称属性。

    【讨论】:

      【解决方案3】:

      尝试为您的输入定义一个名称属性,因为使用 ngModel 需要定义一个名称。 检查文档以获取更多详细信息: Building a template-driven form

      【讨论】:

        猜你喜欢
        • 2017-02-10
        • 2022-01-26
        • 2017-03-13
        • 1970-01-01
        • 2020-08-26
        • 2012-10-24
        • 2023-01-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多