Home > OS >  FormControlName must be used with a parent FormGroup directive when FormGroup is passed to child com
FormControlName must be used with a parent FormGroup directive when FormGroup is passed to child com

Time:03-25

Parent Component

  <form [formGroup]="User">
    
    <app-radioButton [group]="user"></app-radiobuton>
    
    </form>

In Radio Component html

<mat-radio-button  [formControlName]="name" > <mat-radio-button>

in .ts of Radio component

export class RadioComponent{
@Input() group: FormGroup;
}

Giving error as above. Not sure what wrong am i doing.

CodePudding user response:

The reason why its failing its because Angular is waiting for FormGroupDirective on any of parent - child elements. So:

In child component please declare:

@Component({
  selector: 'child',
  templateUrl: './child.component.html',
  viewProviders: [{ provide: ControlContainer, useExisting: FormGroupDirective }]
})

OR

You can use formControl in the child component:

<mat-radio-button  [formControl]="name" > <mat-radio-button>

CodePudding user response:

In your code there is [formGroup]="User" and you pass to child component [group]="user". Why there is different data provided: User and user?

If you want to use your FormGroup the way as you done, - just make your form group wrapping for a child control in the child component too:

<ng-container [formGroup]="group">
  <mat-radio-button [formControlName]="name"><mat-radio-button>
</ng-container>

The other way is to make a more proper component structure:

<form [formGroup]="User">
  <app-radioButton [formControlName]="name"></app-radiobuton>
</form>

And inject control in the child component. You can check how to do it here

  • Related