Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing FormGroup instance from within directive attached to <form>

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?

like image 211
Vladimir Prudnikov Avatar asked Dec 08 '25 06:12

Vladimir Prudnikov


2 Answers

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>
like image 174
tarek khachnawi Avatar answered Dec 09 '25 21:12

tarek khachnawi


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) { }
like image 27
Guilherme Eduardo Bittencourt Avatar answered Dec 09 '25 22:12

Guilherme Eduardo Bittencourt