I'm trying to add a custom directive to the form tag and then get the inputs that use the directive formControlName to filter them by formControl and then add the mat error component dynamically to it.
I've been looking for some solutions. The best way would be that there is a token that I could use and it gets both the directive and the containerRef also so then I could filter by the directive and once I have the element use its containerRef to add to it the mat error component
@Directive({
selector: '[appFormInstance]',
})
export class FormInstanceDirective {
@Input('appFormInstance') form: FormGroup;
@ViewChildren(FormControlName) formControls: QueryList<FormControlName>;
@ViewChildren(FormControlName, { read: ViewContainerRef }) formControlContainerRefs: QueryList<ViewContainerRef>;
createMatErrorFunction(notValidProperty: string): void {
const matErrorFactory = this.componentFactoryResolver.resolveComponentFactory(MatError);
const formControlName = this.formControls.find((formControl) => { return formControl.name === notValidProperty });
// Then....???
}
}
Well I have achieved it doing
var viewContainerRef = this.formControlContainerRefs.find((ref) => ref.element.nativeElement.getAttribute('formcontrolname') === notValidProperty);
var componentRef = viewContainerRef.createComponent(matErrorFactory);
but I still not feel comfortable with this solution.