angular - 尽管导入了表单模块 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 { }
解决方案
抛出异常,因为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 元素。
推荐阅读
- azure-powershell - 在 Azure Powershell 中执行 New-AzPolicyDefinition 时出现“意外字符”错误
- jsf - 当我选择区域时,JSF 中的 Dependend dropDown 依赖区域应该来,当我选择区域依赖时,城市应该来等等
- java - 在netty上运行spring mvc合理吗?
- go - 如何在 golang 中从 Gherkin 数据表中输入布尔值?
- c# - 如何使用 GeckoFX 60 的评估脚本方法获取 youtube 视频的上传日期?
- javascript - Discord JS 音乐机器人的问题
- java - 普罗米修斯端点中缺少 Spring Boot Webclient 指标
- jenkins - Jenkins 基于角色的授权 - 如何限制特定项目对组的访问?
- javascript - 如何正确使用 parseInt 从 chrome 扩展中选择/检查 span 元素
- c# - 如何将 ngrok 与 BOT 模拟器连接?