【发布时间】:2019-02-21 10:32:00
【问题描述】:
当我将自定义 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);
}
我得到的错误:
ERROR 错误:未捕获(承诺):错误: StaticInjectorError(AppModule)
[MatInput -> NgControl]:
StaticInjectorError(Platform: core)[MatInput -> NgControl]:
NullInjectorError:没有 NgControl 的提供者!
错误: StaticInjectorError(AppModule)[MatInput -> NgControl]:
StaticInjectorError(Platform: core)[MatInput -> NgControl]:
NullInjectorError: NgControl 没有提供者!
我知道这与依赖注入有关,我试图在整个互联网上寻找解决方案。到目前为止没有成功。
感谢大家的帮助。
【问题讨论】:
标签: angular typescript