当表单提交按钮位于父组件中时,如何将数据从子组件获取到父组件中?

时间:2019-05-09 11:47:11

标签: javascript angular angular7

我有两个组成部分:

父组件HTML:

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

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

父组件TS: 在这里,我试图测试ViewChild是否可以正常运行。我从父组件的子组件中获得了一个属性值。

export class ParentComponent implements OnInit {

  @ViewChild(ChildComponent) childReference;
  parentString: string;

  constructor(
    private cdRef: ChangeDetectorRef,
  ) { }

  ngOnInit() {
  }


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

在子组件html中,我有几个<mat-form-field>输入:

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

但是当实际的提交按钮位于父级中时,如何从父级组件中的子级组件正确获取matInput值?

2 个答案:

答案 0 :(得分:0)

我会在子组件上创建一个public getData() {}函数,该函数返回子组件的数据。父提交看起来像

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

在您的示例中,您似乎试图从多个子级获取数据,在这种情况下,您将必须使用ViewChildren

我还将考虑使父级具有Angular form,并重组您的组件,以使子级组件是与该表单一起使用的自定义输入。请参阅在this tutorial

中创建的名为state-selector的自定义输入组件

答案 1 :(得分:0)

如果您的项目有Redux设置。您应该使用redux。 Redux可以解决类似类型的问题。