在父级中单击按钮时如何将数据从子级传递给父级

时间:2021-02-04 17:26:34

标签: javascript angular typescript

我是角度的新手。我有一个大表格。我想让它模块化。这就是为什么我创建了多个较小的子组件以及我在主父组件中使用的所有组件选择器。我在 save 组件中有 parent 按钮,单击保存按钮时,应为 api 调用发送表单(子组件)的所有数据。

我知道如何使用 @Output 将数据从子级发送到父级,但我只知道,当我单击子组件中的某个按钮将数据从子级发送到父级时, 但就我而言,我的子组件中没有任何按钮。那么有没有什么有效的方法可以达到同样的目的?或者我不应该使用这种方法?或者有人在stackblitz中有工作示例吗?

提前致谢!!!

1 个答案:

答案 0 :(得分:1)

如果你作为 @Input 传递一个对象(这是一个变量,它的值是一个对象 - 不是一个字符串或数字),你不必担心使用@Output 否则你需要做“某事”来获得孩子们的价值观。简单的方法是在您的孩子中使用模板引用。所以你有,例如<​​/p>

<child-one #childOne ...></child-one>
<child-two #childTwo ...></child-two>
<child-three #childThree ...></child-three>
<button (click)="submit(childOne,childTwo,childThree)">submit</button>

submit(childOne:any,childTwo:any,childThree:any){
   //if, e.g. you has a variable in child-one, child-two and child-three called data you can use
   this.data={dataOne:childOne.data,dataTwo:childTwo.data,dataThree:childThree.data}
   //remember that you can "reach" all the variables public in your children 
   // as, childOne.name_of_variable
}

其他配置,给我们更多的数据:)

相关问题