Multiple child component inside form - Angular 2

2020-02-26 13:11发布

问题:

I am working on big form, so i plan to truncate the form into multiple child components which helps for easy integration and maitainbility. Using form builder i am trying to implement this.

mainform.html

    <form novalidate (ngSubmit)="onSubmit(formDetail);" [formGroup]="formDetail">
      <label>
        <span>Name</span>
          <input
          type="text"
          placeholder="Enter emp name"
          formControlName="name">
      </label>
      <app-userinfo></app-userinfo> <!-- Child component 1 -->
      <app-useracc></app-useracc> <!-- Child component 2 -->
    </form>

mainform.ts

export class MainformComponent implements OnInit {
  formDetail: FormGroup;
  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
      this.formDetail= this.formBuilder.group({
        name:'',
      userinfo: this.formBuilder.group({
        userid: '',
        userph: ''
      }),
      useracc: this.formBuilder.group({
        useracc: '',
        usertransfer: ''
      })
    });
  }
  onSubmit(value:User){
    debugger;
  }
}

Console.log

formControlName must be used with a parent formGroup directive.  You'll want to add a formGroup

Is it possible to nested form component as a seperate child ?

回答1:

You need to use Input() and pass that sub-FormGroup to the child. I changed it a bit here and made the group named useraccount instead of useracc to separate the control from the group:

Your sub group for useraccount in your parent:

  ...
  useraccount: this.formBuilder.group({
    useracc: '',
  })
  ...

So, the related child component tag in the parent should look something like this:

<app-useracc [useraccount]="formDetail.controls.useraccount"></app-useracc>

And then add input in your child component:

@Input() useraccount: FormGroup;

and template could look like this:

<div [formGroup]="useraccount">
  <input formControlName="useracc">
</div>

Working sample