【问题标题】:ngModel is not working (Forms Module I have imported)ngModel 不工作(我已导入的表单模块)
【发布时间】:2021-11-27 00:23:58
【问题描述】:

我已导入forms module。我也包含在imports 部分中,但仍然出现错误。它仅突出显示 html 文件中的错误。我无法理解这个问题。

<textarea rows="6" [(ngModel)] ="enteredValue"  ></textarea>
<hr>
<button (click)="onAddPost()">Save Post</button>

<p>{{ newPost }}</p>

组件文件:-

import { Component  } from "@angular/core";
@Component({
    selector : 'app-post-create',
    templateUrl: './post-create.component.html'
})
export class PostCreateCompomnet{

    newPost ='I am Genius';

    onAddPost(){
        this.newPost= this.enteredValue;  // this is the value of ngModel
    }

}

应用模块

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

@NgModule({
  declarations: [
    AppComponent,
    PostCreateCompomnet

  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

谁能帮我理解这个问题。我是Angular的新手

【问题讨论】:

  • 请将您的组件代码添加到您的问题中。此外,如果您使用 VS Code 插件(如 Angular 语言服务),它会注册错误,直到您的组件成为模块的一部分。
  • 你检查了enteredvalue是否已经在相应的component.ts文件中声明了?还要检查是否区分大小写。
  • 谢谢.....我已经添加了组件和模块文件的代码

标签: angular angular-material angular-ngmodel angular2-ngmodel


【解决方案1】:

需要修改component.ts文件如下图,

export class PostCreateCompomnet {

  newPost = 'I am Genius';
  enteredValue: string; // Missing declaration

  onAddPost() {
    this.newPost = this.enteredValue;
  }

}

enteredValue 的声明丢失。

【讨论】:

  • 非常感谢 Utkarsh。
猜你喜欢
  • 2019-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-12
  • 2018-01-26
  • 1970-01-01
  • 2011-11-06
  • 2021-10-29
相关资源
最近更新 更多