Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My nested Angular reactive form is not getting the FormGroup from the parent component

I came across Kara Erickson's demo of Angular forms at AngularConnect 2017, on YouTube. The part I'm specifically interested is where she describes nested reactive forms

I've done everything as Kara describes, but I end up getting a null parentForm no matter what I try.

I've reproduced a simplified version of my code below. The problem is that in the child-form component I am getting null.

// PARENT COMPONENT

@Component({
  selector: 'parent-form',
  styleUrls: ['./parent-form.component.css'],
  template: `
    <form [formGroup]="createAlbumProfileForm" (ngSubmit)="onFormSubmitted($event)">
        <input type="text" placeholder="Something unique to parent form"/>
        <child-form></child-form>
    </form>
  `
})
export class ParentFormComponent implements OnInit {

  parentForm: FormGroup;

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.parentForm = this.formBuilder.group({
      yoloField: this.formBuilder.control('')
    });
  }

// CHILD COMPONENT

@Component({
    selector: 'child-form',
    styleUrls: [ './child-form.component.scss' ],
    viewProviders:[ { provide: ControlContainer, useExisting: FormGroupDirective } ],
    template: `
      <div formGroupName="songName" class="form-group"></div
    `
})
export class ChildFormComponent implements OnInit {
    childForm: FormGroup;

    constructor(private parentForm: FormGroupDirective) {
        this.childForm = parentForm.form; // null
    }
}
like image 395
CodyBugstein Avatar asked Mar 06 '23 19:03

CodyBugstein


1 Answers

It seems like it is problem with life cycle of the components: in video FormGroup is initialized in constructor of parent component but in your example you initialize it OnInit. The problem is that child's constructor is called before parent's OnInit that is why you are getting null.

like image 101
Yevgeniy.Chernobrivets Avatar answered Apr 03 '23 16:04

Yevgeniy.Chernobrivets