HTML
<form [formGroup]="form">
<input type="text" formControlName="name" class="form-control" />
<div *errorFeedback name="name" class="error-feedback"></div>
</form>
Form Directive.
@Directive({
selector: 'form'
})
export class FormGroupErrorDirective implements OnInit, AfterContentChecked {
@ContentChildren(ErrorFeedbackDirective) errorFeedbackDirectives: QueryList<ErrorFeedbackDirective>;
ngAfterContentChecked(): void {
this.errorFeedbackDirectives.forEach(dir => {
// ???? How can I get this.formGroup ???
dir.formControl = this.formGroup.get(dir.formControlName);
});
}
}
*errorFeedback Directive
// tslint:disable:directive-selector
@Directive({
selector: '[errorFeedback]',
})
export class ErrorFeedbackDirective implements OnInit {
// tslint:disable:no-input-rename
@Input('errorFeedback')
name: string;
formControl!: FormControl;
constructor(private el: ElementRef,
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef) { }
ngOnInit() {
}
}
How can I get access to the FormGroup directive instance from within FormGroupErrorDirective?
What I'm trying to do here is pass the FormControl instance to the *errorFeedback directive. I'll then use it for observing status changes and errors there.
Or is there any better way to get access to FormControl instance inside *errorFeedback?
You can use FormGroupDirective class in your directive constructor:
constructor(private fg: FormGroupDirective) {
this.fg = fg;
console.log(this.fg.form)// print your form group
}
In your template:
<div [formGroup]="editFormGroup" yourDirective>
</div>
It's possible to access the FormGroup by declaring in directive constructor method a property like this:
import { ControlContainer } from '@angular/forms';
constructor(private readonly form: ControlContainer) { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With