angular - Angular:自定义formControl上的指令导致错误
问题描述
当我将自定义idNumber指令添加到子 HTML 元素时,一切正常。我想在父类中使用它。然而那是行不通的。
// custom directive ////////
@Directive({
selector: "[idNumber]"
})
export class IcoDirective implements OnInit {
formControl: FormControl;
constructor(private control: NgControl) { }
ngOnInit() {
this.formControl = <FormControl>this.control.control;
this.addValidators(this.formControl);
}
addValidators(formControl: FormControl) {
formControl.setValidators(Validators.compose(
[... some validators...]
));
}
// child HTML ////////
<mat-form-field>
<input matInput idNumber // if I put the directive here, all works fine.
[formControl]="idNumberFormControl"
</mat-form-field>
// child TS ////////
ngOnInit() {
this.idFormControl = new FormControl();
this.idFormControl.valueChanges.subscribe(value => {
this.manageUserInput(this.idFormControl );
});
}
insertIntoForm(parentFormGroup: FormGroup): void {
parentFormGroup.addControl(this.name, this.idFormControl );
}
// parent HTML ////////
<custom-input-string
idNumber // if I put the directive here (not in child), I get an error.
[name]="'idNumber'">
</custom-input-string>
// parent TS ////////
@ViewChild(CustomInputStringComponent) child: CustomInputStringComponent;
ngAfterViewInit() {
setTimeout(() => {
this.child.insertIntoForm(this.signupForm);
}, 0);
}
我得到的错误:
错误错误:未捕获(承诺中):错误:StaticInjectorError(AppModule)
[MatInput -> NgControl]:
StaticInjectorError(平台:核心)[MatInput -> NgControl]:
NullInjectorError:没有NgControl的提供者!
错误:StaticInjectorError(AppModule)[MatInput -> NgControl]:
StaticInjectorError(Platform: core)[MatInput -> NgControl]:
NullInjectorError: No provider for NgControl!
我知道这与依赖注入有关,我试图在整个互联网上寻找解决方案。到目前为止没有成功。
谢谢大家的帮助。
解决方案
那是因为你不再是输入。
您必须使用ContentChild
来获取您想要的组件,然后使用该组件的控件。
Stackblitz(基于您之前的问题)
@ContentChild(CustomComponentComponent) component: CustomComponentComponent;
constructor(
) { }
ngAfterViewInit() {
this.component && this.component.control.setValidators([Validators.required]);
}
推荐阅读
- node.js - Node/Express:从 URL 中获取 req.query 值并将其转换为 UNIX 时间戳
- dart - Flutter 无法识别有效的导入
- php - 在 Behat/Mink FeatureContext 中使用 Laravel Eloquent
- python - 将列表列表转换为 numpy 数组会产生不同的结果
- php - 考虑“除所有字符”类型正则表达式中的转义引号
- java - SpringBoot - Register a bean before @Component's get scanned
- python - 用户不存在,也没有重定向到 django 项目中创建的租户
- coinbase-api - coinbase-api 有什么 Swagger 吗?
- sparql - 维基数据示例和子类
- php - 集成 Apple Pay 时,如何将 Stripe 的 javascript paymentRequest 与 PHP 处理服务器端混合使用