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

时间:2018-09-17 13:20:47

标签: 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);
}


我得到的错误:
错误错误:未捕获(承诺):错误:StaticInjectorError(AppModule)
[MatInput-> NgControl]:
StaticInjectorError(平台:核心)[MatInput-> NgControl]:
NullInjectorError:NgControl没有提供者!
错误:StaticInjectorError(AppModule)[MatInput-> NgControl]:
StaticInjectorError(平台:核心)[MatInput-> NgControl]:
NullInjectorError:NgControl没有提供者!

我知道它与依赖注入有关,因此我尝试在整个Internet上寻找解决方案。到目前为止未成功。
谢谢大家的帮助。

1 个答案:

答案 0 :(得分:0)

那是因为您不再需要输入。

您必须使用ContentChild来获取所需的组件,然后使用该组件的控件。

Stackblitz(根据您之前的问题)

@ContentChild(CustomComponentComponent) component: CustomComponentComponent;

constructor(
) { }

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