【问题标题】:How to get the data from child component into the parent component when the form submit button is in the parent component?当表单提交按钮在父组件中时,如何将子组件中的数据获取到父组件中?
【发布时间】:2019-09-27 05:58:36
【问题描述】:

我有两个组件:

父组件 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 wokrs 是否正确。我从父组件中的子组件获取属性值。

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 中,我有几个 &lt;mat-form-field&gt; 输入:

<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 值?

【问题讨论】:

  • 在 Parent 中提交并希望 Child 中的数据?
  • 如果是一个问题,我在子项中有一个输入,当提交按钮在父项中时,我想在父项中获取这些输入值。
  • 你能提供 stackblitz 让我看看吗?

标签: javascript angular angular7


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我将在子组件上创建一个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 的自定义输入组件

    【讨论】:

    • 有了ViewChild@,我只从第一个孩子那里得到孩子的信息。不知何故,老二给我带来了空字符串..
    猜你喜欢
    • 2019-03-07
    • 2021-09-29
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 2018-12-24
    • 2022-01-25
    • 2017-10-19
    相关资源
    最近更新 更多