Search code examples
angularangular-reactive-formsangular-content-projection

Angular14: How to query a form component with ContentChild


Let's say I want to put any form component to a wrapper form field component. How can I query any form component that can use formControl directives.

The wrapper component will be used like this.

@Component({
  selector: 'form-field',
  template: `
    <label >{{label}}</label>
    <ng-content></ng-content>
    <div class="error-message">{{error}}</div>

  `,
  styles: [],
})
export class FormFieldComponent {

  @ContentChild(IDontKnowWhatToPutHere) formComponent: IDontKnowWhatToPutHere 

  @Input() label!: string;

  error: string = "";

  constructor() {}

  ngAfterContentInit() {
    this.listenToErrorsAndSetError(this.formComponent.control)
  }
}

Then, this component can be used like this.

...
<form-field label="myLabel">
  <input formControlName="myControlName">
</form-field>
<form-field label="myLabel2">
  <custom-multiselect formControlName="myControlName2"></custom-multiselect>
</form-field>
...

Is something like this possible?


Solution

  • You can select all form elements by NgControl directive. But ContentChild decorator will select only the first one element. Use ContentChildren to access all of them.

    Example:

    @ContentChild(NgControl) formComponent: NgControl