[英]How to get the data from child component into the parent component when the form submit button is in the parent component?
I have two components: 我有两个组成部分:
Parent component HTML: 父组件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. 父组件TS:在这里,我试图测试ViewChild是否正确,并且确实如此。 I get a property value from child in my parent component.
我从父组件中的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();
}
In my child component html I have a couple of <mat-form-field>
inputs: 在我的子组件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>
But how to properly get an matInput values from child component in the parent component when the actual submit button is in the parent? 但是,当实际的提交按钮位于父组件中时,如何从父组件中的子组件正确获取matInput值?
I would create a public getData() {}
function on the child component that returns the data of the child component. 我将在子组件上创建一个
public getData() {}
函数,该函数返回子组件的数据。 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 . 看起来你试图从你的例子中的多个孩子那里获取数据,在这种情况下你将不得不使用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. 我还会考虑让父级具有Angular表单 ,并重构组件,以便子组件是与该表单一起使用的自定义输入。 See the custom input component called
state-selector
created in this tutorial 请参阅本教程中创建的名为
state-selector
的自定义输入组件
If you have redux setup with your project. 如果您对项目进行了redux设置。 You should go with redux.
你应该选择redux。 Redux is buildup to solve similar type of problems.
Redux正在积累以解决类似的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.