How to pass reactive form data between child to parent components with out using services

后端 未结 2 1976
别那么骄傲
别那么骄傲 2021-01-13 02:05

We would like to consume child reactive form data from parent when we click on parent button. Currently we are using viewchild for getting the child cpomponent reference. We

相关标签:
2条回答
  • 2021-01-13 02:28

    Wrap your child form Inside form element so that you can submit your child form from parent, Then Inject FormGroupDirective in child component to get ref of parent form

    <form (ngSubmit)="save()" [formGroup]="detailsForm"> 
        <app-child></app-child>
        <button type="button">Save</button>
     </form>
    

    Then use controlContainer to provide the existing FormGroupDirective in child component

    childcomponent.ts

      form;
      constructor(private fb: FormBuilder, @Host() private parentFor: FormGroupDirective) { }
    
      ngOnInit() {
        this.form = this.parentFor.form;
        //Add FormControl as per your need
        this.form.addControl('child', this.fb.group({
          name: "",
          email: ""
        }))
    
      }
    

    child.component.html

    <form formGroupName="child">
      <input formControlName="name">
      <input formControlName="email">
    </form>
    

    Example:https://stackblitz.com/edit/angular-xusdev

    0 讨论(0)
  • 2021-01-13 02:35

    If use a "referenceVariable" you has access to all the public variables and function of the "child"

    <button (click)="click(mychild)"></button>
    <child #mychild></child>
    
    click(mychild.any)
    {
       console.log(mychild.detailsForm);
    }
    

    Anyway, I think you want a child that belong to a Form. For this you can use viewProviders in child

    viewProviders: [
        {
          provide: ControlContainer,
          useExisting: FormGroupDirective
        }
      ]
    

    As this link show

    0 讨论(0)
提交回复
热议问题