首页 > 解决方案 > ERROR 错误:NG0201:在 NodeInjector 中找不到 NgControl 的提供程序

问题描述

我完全没有想法了。我想使用 Reactive Forms Module,所以我在 app.module.ts 中导入了它

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

@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  imports: [
    ...
    ReactiveFormsModule,
    ...
  ],
  providers: [],
  bootstrap: [AppComponent]
})

在我的组件中,我定义了:

import { Component, OnInit} from "@angular/core";

import { FormControl, FormGroup } from '@angular/forms';

@Component({
    ...
})

export class SearchComponent implements OnInit{
    //Variablen
    form: FormGroup;
    
    //Konstruktor
    constructor(){}

    //Methoden
    ngOnInit(){
        this.form = new FormGroup({
            'title': new FormControl(null)
        });
    }

    showValue(){
        console.log(this.form.get('title'));
    }
}

编译效果很好,但是在显示它时它会崩溃,并在浏览器控制台中显示以下错误:“core.js:6156 ERROR Error: NG0201: No provider for NgControl found in NodeInjector.”

你们中有人知道出了什么问题吗?

我真的很感激任何提示。

非常感谢!

标签: angulartypescriptweb-applications

解决方案


要完成这项工作,您必须在 @NgModule 中导入 ReactiveFormsModule ,正如您的问题所暗示的那样,这是 ViewsModule 。因为 FormControl 是作为 ReactiveFormsModule 的一部分而不是 FormsModule 的一部分公开的。

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

@NgModule({
  imports: [..., ReactiveFormsModule, ...],
  ...
})
export class ViewsModule {...}

推荐阅读