Search code examples
angularformsform-control

How do I get access to from control from another component in Angular?


I have form with form controls in component A. I've decided to move some form controls to separate component B in order to prevent code duplicates in other components.

A.html:

<form [formGroup]="editForm">
  <B [formControllerName]="'name'" ></B>
  <!-- Other form controls -->
</form>

B.html:

<select class="form-select" formControlName="{{formControllerName}}">
  <!-- Options -->
</select>

I got this error: Error: NG01050: formControlName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class).

How I can get access to form controller from component A?


Solution

  • It's possible using viewProviders, see, e.g. this SO about FormArray

    A more simple

    @Component({
      selector: 'hello',
      template: `<h1>Hello </h1>
          <input [formControlName]="name"/>
      `,
      viewProviders:[{ provide: ControlContainer, useExisting: FormGroupDirective }]
    })
    export class HelloComponent  {
      @Input() name: string;
      
      constructor(){}
    }
    

    You can use

    <form [formGroup]="form">
      <hello [name]="name" > </hello>
    </form>
    

    in .ts

      name = 'name';
      form=new FormGroup({
        name:new FormControl()
      })
    

    See stackblitz

    The another way is pass the own FormControl and use

       control:FormControl
       @Input('control') set _control(value){
           this.control=value as FormControl
       }
    
       <input [formControl]="control">
    

    You use as

       <hello [control]="form.get('name')" > </hello>