1
votes

I have two components:

Parent component HTML:

<parent-component>
    <child-component [input]="inputValue"> </child-component>
    <child-component [input]="inputValue"> </child-component>

    <button mat-stroked-button> Submit </button>
</parent-component>

Parent component TS: here I was trying to test if ViewChild wokrs correctly and it is. I get a property value from child in my parent component.

export class ParentComponent implements OnInit {

  @ViewChild(ChildComponent) childReference;
  parentString: string;

  constructor(
    private cdRef: ChangeDetectorRef,
  ) { }

  ngOnInit() {
  }


  ngAfterViewInit() {
    this.parentString = this.childReference.exampleChild;
    this.cdRef.detectChanges();
  }

In my child component html I have a couple of <mat-form-field> inputs:

<form [formGroup]="myForm">
    <mat-form-field>
           <input matInput formControlName="myInput">
      </mat-form-field>
     <mat-form-field>
           <input matInput formControlName="myInput2">
      </mat-form-field>
</form>

But how to properly get an matInput values from child component in the parent component when the actual submit button is in the parent?

2
Submit in Parent and want data in Child? - Prashant Pimpale
If it's a question, I have an inputs in child and I want to get those input values in parent when the submit button is in the parent. - HELPME
Can you provide stackblitz So I can have a look at? - Prashant Pimpale

2 Answers

0
votes

I would create a public getData() {} function on the child component that returns the data of the child component. The parent submit would look something like

public submit() {
    const data = this.childReference.getData();
    // do whatever you need to do with the data from child
}

It looks like you're trying to get data from multiple children in your example, in which case you'll have to use ViewChildren.

I would also consider making the parent have an Angular form, and restructuring your components so that the child components are custom inputs that work with that form. See the custom input component called state-selector created in this tutorial

0
votes

If you have redux setup with your project. You should go with redux. Redux is buildup to solve similar type of problems.