Skip to content

Instantly share code, notes, and snippets.

@hollygood
Created April 25, 2019 14:34
Show Gist options
  • Save hollygood/4e6de69a74d33661319ccf5aa74cbdfb to your computer and use it in GitHub Desktop.
Save hollygood/4e6de69a74d33661319ccf5aa74cbdfb to your computer and use it in GitHub Desktop.
Creating a Reactive Form in Parent Component or Child Component

Example 1

// parent.component.ts
form: FormGroup;

ngOnInit() {
   this.form = new FormGroup({}); // create empty FormGroup in order to addControls in nested components
}

// parent.component.html
<child-component
  [childForm]="form"
  [data]="data"
></child-component>

// child.component.ts
@Input() childForm: FormGroup;
@Input() data;

ngOnInit() {
   this.childForm = this.dynamicService.generateFormGroup(this.data); // function to generate data
}

Example 2

// parent.component.html
<child-component
  [data]="data"
></child-component>

// child.component.ts
@Input() data;

ngOnInit() {
   this.form = this.dynamicService.generateFormGroup(this.data); // function to generate data
}

So the main difference is create the FormGroup in Parent component or Child Component. If the Form is dependent, sometimes we'll just create the Form in child component. However, if you create it in child component (Example 2), the issue may occur is that when Parent Component loading new data and pass it to child component, the Form is still contains the previous generated controls, and if you use complex dynamic generate form controls like me, the control values will be showing twice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment