I'm creating a custom angular component which shows an error tooltip when my FormControl (Reactive Forms) is invalid. But I don't know how I can access the FormControl inside my custom component to check whether or not it is marked as valid.
What I want to accomplish
<div [formGroup]="form">
<input formControlName="name" type="text" />
<custom-validation-message formControlName="name">My special error message!</custom-validation-message>
</div>
Already encountered stuff
ERROR Error: No value accessor for form control with name: 'surveyType'
Fixed this by implementing ControlValueAccessor with NG_VALUE_ACCESSOR even though I don't want to alter the value. I also added an injector to access the NgControl.
import { Component, OnInit, Injector } from '@angular/core';
import { NgControl, ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'custom-validation-message',
templateUrl: './validation-message.component.html',
providers: [{
provide: NG_VALUE_ACCESSOR, multi: true, useExisting: ValidationMessageComponent
}]
})
export class ValidationMessageComponent implements ControlValueAccessor, OnInit {
public formControl: any;
constructor(private injector: Injector) {
super();
}
public ngOnInit(): void {
const model = this.injector.get(NgControl);
this.formControl = model.control;
}
public writeValue(obj: any): void {
}
public registerOnChange(fn: any): void {
}
public registerOnTouched(fn: any): void {
}
public setDisabledState?(isDisabled: boolean): void {
}
}
Current Problem The model.control is undefined. After inspecting the model I found out that the model is as good as empty only the _parent is a full representation of my form. The model._parent.controls does contain all the controls of my form. But still I don't know the current control.