简体   繁体   中英

How to pass controls in parent component sent from child component?

https://stackblitz.com/edit/child-component-ki8tvu?file=app%2Fchild.component.ts , check my code here

app.component.html:

<div [formGroup]="myform">
  <h1>Good bye</h1>

  <child-component (guestData)="fetchGuestData($event)"></child-component>
</div>

app.component.ts:

import { Component } from '@angular/core';
import { OnInit } from '@angular/core/src/metadata';
import {
  AbstractControl,
  FormArray,
  FormBuilder,
  FormControl,
  FormGroup,
  Validators,
} from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  myform: FormGroup;

  constructor(private fb: FormBuilder) {}
  ngOnInit() {
    this.myform = this.fb.group({});
    this.myform.addControl('responseData', new FormArray([]));
  }

  fetchGuestData(event) {
    const temp= this.myform.controls['responseData'] as FormArray;
    temp.push(event);
    console.log(this.myform);
  }
}

child.component.ts:

import { Component, Input } from '@angular/core';
import { AfterViewInit, EventEmitter, OnInit, Output } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'child-component',
  template: `
  <div class="row">
    <form class="col-md-12" [formGroup]="form">
  
      <div class="question font-weight-500 my-2">
        {{question.question}}
      </div>
      <ng-container *ngFor="let choice of question.answer.data;">
        <div class="d-flex align-items-center primary-input-radio mb-2">
          <div class="mr-2">
            <input
              type="radio"
              name="multiple-choice"
              aria-label="multiple-choice"
              [checked]="this.form.controls['answer'].value === choice.option"
              (click)="setValue(choice.option)">
          </div>
          <div class="text-break">
            {{choice.option}}
          </div>
        </div>
      </ng-container>
  
      <div class="answer paragraph my-2" *ngIf="(question.answer?.type === 'paragraph')">
        <textarea class="form-control fs-16"
                  placeholder="Your answer"
                  formControlName="answer">
        </textarea>
      </div>
     </form>
  </div>
  `,
  styles: [`h1 { font-family: Lato; }`],
})
export class ChildComponent implements OnInit, AfterViewInit {
  @Output() guestData = new EventEmitter();

  question = {
    question: 'where r u from',
    answer: {
      type: 'multipleChoice',
      data: [{ option: 'delhi' }, { option: 'noida' }],
    },
    isRequired: true,
  };

  form: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.form = this.fb.group({
      question: [this.question.question],
      answer: [''],
    });
    this.form.valueChanges.subscribe((res) => {
      this.guestData.emit(res);
    });
    this.guestData.emit(this.form);
  }

  setValue(e) {
    console.log(e);
    if (e === this.form.value.answer) {
      this.form.patchValue({
        answer: null,
      });
      return;
    }
    this.form.patchValue({
      answer: e,
    });
  }
}

getting this error while fetching data in parent from child component,

ERROR TypeError: control.setParent is not a function
    at FormArray._registerControl (model.js:3293:20)
    at FormArray.push (model.js:2790:7)
    at AppComponent.fetchGuestData (VM5508 app.component.ts:26:14)
    at Object.eval [as handleEvent] (VM5650 AppComponent.ngfactory.js:32:31)
    at handleEvent (view.js:136:41)
    at callWithDebugContext (services.js:864:6)
    at Object.debugHandleEvent [as handleEvent] (services.js:435:2)
    at dispatchEvent (util.js:171:6)
    at eval (provider.js:182:2)
    at SafeSubscriber.schedulerFn [as _next] (event_emitter.js:169:27)

getting this error while fetching data from child, Suggest something to solve this issue

You can use this solution:


this.form.valueChanges.subscribe((res) => {
  this.guestData.emit(this.form.get('answer') as FormGroup);
});

https://stackblitz.com/edit/child-component-mapqnu?file=app%2Fchild.component.ts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM