angulartypescriptformsparent-child

Nested form in child component without FormGroup


I want to be able to reuse part of my form elsewhere, so I wanted to separate it into it's own component. I still want to submit the form through the parent component - no button or anything in the child. I also don't want to use FormGroup if I can help it. Is this possible?

This is what I am trying to make work:

<parent>
  <form #f="ngForm" (ngSubmit)="onSubmit(f)" id="f">
    <child></child>
    <input type="checkbox" id="terms" #terms="ngModel" ngModel name="terms"> 
    <input type="submit" id="btnSubmit">
  </form>
</parent>

Ideally the child would return an object with the form information like so (if this is impossible but something else can be done that's ok too):

@Component({
   selector: 'child', 
   ...
})
export class ChildComponent implements OnInit {
  ...
  createObject(form:NgForm) {
    let user = new userProfile(); 
    user.email = form.controls["email"].value;
    user.username = form.controls["username"].value;
    ...
    return user;
  }
}

Solution

  • Use @ViewChild in the parent to call a method in the child that extracts form data.

    Reference: https://angular.dev/api/core/ViewChild