Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

no provider for ngControl [FormControl] Angular 6

I am learning Angular. While the official tutorial has worked quite well for me, I am stuck with the 'hello world' of Reactive Forms. I am following https://angular.io/guide/reactive-forms. I have created a new component, in an other wise working project, to make an input text box using ReactiveForm. The template html is as follows:

    <div>
        <label>
          Name:
          <input type="text" [formControl]="name">
        </label>
    </div>

The component class looks as follows

import { Component, OnInit } from '@angular/core';
import {FormControl} from '@angular/forms';

@Component({
  selector: 'app-party-worker',
  templateUrl: './party-worker.component.html',
  styleUrls: ['./party-worker.component.scss']
})
export class PartyWorkerComponent implements OnInit {
  name = new FormControl('');
  constructor() { }
  ngOnInit() {
  }
}

The error in the browser reads something like this.

Uncaught Error: Template parse errors:
No provider for NgControl ("
    <label>
      Name:
      [ERROR ->]<input type="text" [formControl]="name">
    </label>
  </div>"): ng:///ViewsModule/PartyWorkerComponent.html@3:6

And yes, I have imported ReactiveFormsModule. My angular version, if it is revealed by ng --version is as follows

Angular CLI: 7.0.5
Node: 11.1.0
OS: darwin x64
Angular:
...

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.10.5
@angular-devkit/core         7.0.5
@angular-devkit/schematics   7.0.5
@schematics/angular          7.0.5
@schematics/update           0.10.5
rxjs                         6.3.3
typescript                   3.1.6

I fail to understand as to what is it that I am doing wrong. Any help is appreciated.

question from:https://stackoverflow.com/questions/53406049/no-provider-for-ngcontrol-formcontrol-angular-6

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To make this work you'll have to import the ReactiveFormsModule in your @NgModule which is the ViewsModule as your question suggests. As FormControl is exposed as a part of ReactiveFormsModule and NOT the FormsModule.

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...