Angular:自定义 formControl 上的指令导致错误

标签 angular typescript

当我将自定义 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 Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)
[MatInput -> NgControl]:
StaticInjectorError(Platform: core)[MatInput -> NgControl]:

NullInjectorError: No provider for NgControl!
Error: StaticInjectorError(AppModule)[MatInput -> NgControl]:
StaticInjectorError(Platform: core)[MatInput -> NgControl]:

NullInjectorError: No provider for NgControl!

我知道这与依赖注入(inject)有关,我尝试在互联网上寻找解决方案。到目前为止还没有成功。
感谢大家的帮助。

最佳答案

那是因为您不再处于输入状态。

你必须使用ContentChild来获取你想要的组件,然后使用该组件的控件。

Stackblitz (根据您之前的问题)

@ContentChild(CustomComponentComponent) component: CustomComponentComponent;

constructor(
) { }

ngAfterViewInit() {
  this.component && this.component.control.setValidators([Validators.required]);
}

关于Angular:自定义 formControl 上的指令导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52368767/

相关文章:

javascript - Angular 表单提交事件在父组件和子组件之间触发两次

json - '+' 字符在 HttpParams Angular 6 中转换为空格

javascript - Node.js '[object File]' BLOB

javascript - 如何以 Angular 转换数据以校正张量格式?

javascript - 如何在根组件中获取查询参数?

angular - ngOnInit 在 APP_INITIALIZER 完成之前启动

javascript - 过多的变量声明是否会对性能产生重大影响?

javascript - 如何在 typescript 的公共(public)函数中初始化Http导入?

angularjs - Visual Studio Code 提示 *.d.ts 文件中定义的类型为 "Cannot find namespace"

javascript - 如何更改模板中的日期类型? Angular 2+