首页 > 解决方案 > 尽管导入了表单模块 Angular2+,但 CustomDirective 中没有 NgControl 提供者

问题描述

所以,我正在创建一个自定义指令,需要在其中使用表单控件。但是我遇到了一个错误:NgControl 没有提供者;我知道正确的答案是:导入反应表单模块,但我已经导入了!

import { Directive, ElementRef, Input, HostListener, OnDestroy } from '@angular/core';
import { NgControl } from '@angular/forms'
@Directive({
  selector: '[testDirective]'
})
export class TestDirectiveClass implements OnDestroy{

  constructor(private elementRef: ElementRef, c: NgControl ) { }

    ngOnDestroy() {

  }

}

我的组件:

<p testDirective>
  Start editing to see some magic happen :)
</p>

和我的 appModule:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { TestDirectiveClass } from './testDirective.directive';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

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

我的堆栈闪电战

标签: angularformsdependency-injectionimportangular-directive

解决方案


抛出异常,因为p元素缺少[formControlName]指令。接下来是使用 HTML 表单元素,例如input, select, radio button, etc.这是因为 Angular 定义ControlValueAccessor了默认的表单元素,而p仅用于表示文本,它没有input.

app.component.html

<div [formGroup]="form">
  <input testDirective formControlName="testControl">
    Start editing to see some magic happen :)
</div>

app.component.ts

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  implements OnInit{
  name = 'Angular ' + VERSION.major;

  form: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.form = this.fb.group({
      testControl: [null]
    })
  }
}

Angular 文档还说明了以下内容:

所有基于 FormControl 的控制指令扩展的基类。它将 FormControl 对象绑定到 DOM 元素。


推荐阅读