【问题标题】:Angular - There is no directive with "exportAs" set to "ngModel"Angular - 没有将“exportAs”设置为“ngModel”的指令
【发布时间】:2017-10-21 18:14:09
【问题描述】:

以下是 AngularJS 项目中的文件。正如一些帖子中所建议的,我添加了:

ngModel name="currentPassword" #currentPassword="ngModel 

在输入字段中,但仍然出现错误。

package.json

.........
"dependencies": {
        "@angular/common": "^2.3.1",
        "@angular/compiler": "^2.3.1",
        "@angular/core": "^2.3.1",
        "@angular/forms": "^2.3.1",
        "@angular/http": "^2.3.1",
        "@angular/platform-browser": "^2.3.1",
        "@angular/platform-browser-dynamic": "^2.3.1",
        "@angular/router": "^3.3.1",
        "core-js": "^2.4.1",
        "rxjs": "^5.0.1",
        "ts-helpers": "^1.1.1",
        "zone.js": "^0.7.2"
    },
   ...............

change-password.component.html

<form #f="ngForm" [formGroup]="changePasswordForm">
        <div class="form-group">
            <label for="currentPassword">Current Password</label> <input
                placeholder="currentPassword" ngModel name="currentPassword"
                #currentPassword="ngModel" id="currentPassword"
                name="currentPassword" type="text" class="form-control" required
                minlength="6" formControlName="currentPassword">
            </div>
        </div>
        <button class="btn btn-primary" type="submit">Change Password</button>
    </form>

change-password.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators, ControlContainer, FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-change-password',
  templateUrl: './change-password.component.html',
  styleUrls: ['./change-password.component.css']
})
export class ChangePasswordComponent implements OnInit {

  changePasswordForm;

  constructor(formBuilder: FormBuilder) {
    this.changePasswordForm = formBuilder.group({
      currentPassword: new FormControl('', Validators.compose([Validators.required]))
    });
  }

  ngOnInit() {
  }

}

app.module.ts 有导入

............
imports: [
    BrowserModule,
    HttpModule,
    FormsModule,
    ReactiveFormsModule
  ]
...........

我收到以下错误:

未处理的 Promise 拒绝:模板解析错误: 没有将“exportAs”设置为“ngModel”的指令 (“urrent Password ]#currentPassword="ngModel" id="currentPassword" name="currentPassword" type="text" class="form-co"): ChangePasswordComponent@5:4 ;区域:;任务:Promise.then;值:SyntaxError {__zone_symbol__error:错误:模板解析错误: 没有将“exportAs”设置为“ngModel”的指令(“urrent Passwo……} 错误:模板解析错误: 没有将“exportAs”设置为“ngModel”的指令 (“urrent Password ]#currentPassword="ngModel" id="currentPassword" name="currentPassword" type="text" class="form-co"): ChangePasswordComponent@5:4 在 SyntaxError.ZoneAwareError (http://localhost:4200/polyfills.bundle.js:6884:33) 在 SyntaxError.BaseError [作为构造函数] (http://localhost:4200/vendor.bundle.js:64475:16) 在新的 SyntaxError (http://localhost:4200/vendor.bundle.js:5727:16)

【问题讨论】:

    标签: angular angular2-forms angular2-ngmodel


    【解决方案1】:

    可能有两个原因:

    1. 检查您的 app.module.ts 及其下导入的 FormModule(下)是否缺失,imports: []

      从“@angular/forms”导入 { FormsModule };

    2. 如果正确保存所有内容后问题仍然存在。停止服务器并重新运行 ng server

    【讨论】:

      【解决方案2】:
      import { NgModule } from '@angular/core';
      import { BrowserModule } from '@angular/platform-browser';
      import { FormsModule } from '@angular/forms';
      import { AppRoutingModule } from './app-routing.module';
      import { AppComponent } from './app.component';
      import { ContactFormComponent } from './contact-form/contact-form.component';
      
      @NgModule({
        declarations: [
          AppComponent,
          ContactFormComponent
        ],
        imports: [
          FormsModule,
          BrowserModule,
          AppRoutingModule
        ],
        providers: [],
        bootstrap: [AppComponent]
      })
      export class AppModule { }
      

      导入FormsModule 解决了这个问题

      【讨论】:

        【解决方案3】:

        如果您使用角度模板驱动的表单并希望使用#xname="ngModel",您还需要在同一输入中使用[(ngModel)]="mymodel" 指令,当然,将de FormsModule 导入您的app.module,如在上面的其他答案中说过

        【讨论】:

          【解决方案4】:

          这可能会对 Angular 6 中的某个人有所帮助。

          我忘记在我的输入控件中添加ngModel 指令,但在我的表单中添加了#currentPassword="ngModel"。导入等都到位了。

          【讨论】:

            【解决方案5】:

            您正在使用模板驱动和模型驱动表单的奇怪组合。选择其中一个,不要混合这两个。所以这里是模型驱动表单的示例:

            模板中无需设置requiredminlength,我们在组件中处理。我们也不需要任何ngModelname 等,因为我们使用formControlName。同时删除#f="ngForm",因为它与模板驱动的表单有关。所以你的模板应该是这样的:

            <form [formGroup]="changePasswordForm">
              <label for="currentPassword">Current Password</label> 
              <input formControlName="currentPassword">
              <button type="submit">Change Password</button>
            </form>
            

            在构建表单时,我们设置了所有需要的验证器,在本例中为 requiredminLength

            constructor(formBuilder: FormBuilder) {
              this.changePasswordForm = formBuilder.group({
                currentPassword: new FormControl('', 
                      Validators.compose([Validators.required, Validators.minLength(6)]))
              });
            }
            

            原来如此! :)

            我建议你阅读表单,这里是 the guide for template driven formsguide for reactive forms

            编辑:

            对于表单验证,请检查 official docs 进行表单验证。如果您有很多字段,您可能需要调整他们的解决方案,将所有表单错误存储在单独的对象中。

            但这里是检查每个表单控件的表单错误的基本解决方案。因此,以下内容将用于您的验证:

            <small *ngIf="changePasswordForm.get('currentPassword').hasError('required')">Required!</small>
            <small *ngIf="changePasswordForm.get('currentPassword').hasError('minlength')">Minimum 6 chars</small>
            

            您可能还希望在触摸字段时显示错误消息 (??)。您可以在我提供的用于验证的链接中找到所有这些内容:)

            Updated Demo

            【讨论】:

            • 感谢您的回答。如何在输入字段上创建局部变量以获取表单验证错误(不使用#f)?这是为了在 span/div 中显示错误消息。
            • 我编辑了问题并更新了 plunker。另请查看我提供的链接以获取更多信息! :)
            • “表单指南”链接已损坏
            • 感谢@reggaeguitar 提供信息 :) 已修复。
            【解决方案6】:

            添加 import { FormsModule } from '@angular/forms';到您的 app.module.ts 和导入数组中,您需要添加 FormsModule。

            答案很晚,但如果有人在 Angular 5 中遇到问题,你需要这样做。

            【讨论】:

            • 希望早点来,这才是真正的答案
            • @IkelieCyril 在问题中,我们可以看到 OP 在 app 模块中导入了该模块。这不是这个问题的问题。
            猜你喜欢
            • 2018-08-14
            • 2017-10-02
            • 2018-08-30
            • 2017-11-08
            • 2019-02-01
            • 1970-01-01
            • 1970-01-01
            • 2018-05-12
            相关资源
            最近更新 更多