Search code examples
angularangular-content-projection

How can i access to my formControl which is injected in my component?


I have parent component. Inside it i am projecting a input.

<app-form-field>
  <input #input [id]="autoCompleteSearchInput" type="text" autoComplete="off"
   class='input-underline search-bar idented-text' [placeholder]="placeholder" 
   [formControl]="search" />
</app-form-field>

So i am having this control

[formControl]="search"

now i can't find a way to access to the content injected formControl from my AppFormFieldComponent.

I tried with HTML

   <ng-content select=".input-underline"></ng-content>

TS

 @ContentChild(FormControlName, {static: false}) formControl: FormControlName;

ngAfterContentInit() {
  console.log(this.formControl);
}

but it gives me undefined.

How can i acess this form control so i can know what is typed inside input from my component ?


Solution

  • You are using [formControl] so you should use FormControlDirective in your @ContentChild:

    @ContentChild(FormControlDirective, {static: false})
    formControl?: FormControlDirective;
    
    ngAfterContentInit() {
      console.log(this.formControl);
    }