繁体   English   中英

当表单提交按钮位于父组件中时,如何将子组件中的数据导入父组件?

[英]How to get the data from child component into the parent component when the form submit button is in the 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>

父组件TS:在这里,我试图测试ViewChild是否正确,并且确实如此。 我从父组件中的child获取属性值。

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

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

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

看起来你试图从你的例子中的多个孩子那里获取数据,在这种情况下你将不得不使用ViewChildren

我还会考虑让父级具有Angular表单 ,并重构组件,以便子组件是与该表单一起使用的自定义输入。 请参阅本教程中创建的名为state-selector的自定义输入组件

如果您对项目进行了redux设置。 你应该选择redux。 Redux正在积累以解决类似的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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