简体   繁体   English

在Angular 2 +中从父组件调用子组件方法

[英]Call a sub-component method from parent compoent in Angular 2 +

I'm new to Angular, and as the title states, I'm trying to see if this is doable. 我是Angular的新手,正如标题所述,我试图查看这是否可行。

Instead of using the standard way of a sub-component sending data via it's @Output EventEmitter , I would like to have the same concept (without injecting the parent into the child) but with the parent component emitting data to a child. 我不希望使用子组件通过@Output EventEmitter发送数据的标准方式,而是希望具有相同的概念(不将父组件注入子组件),而父组件向子组件发送数据。 Can a parent component emit data to a child? 父组件可以向孩子发送数据吗? If not, why is that so? 如果没有,那为什么呢?

Just to clarify, the sub-component is a form that gets filled in. As soon as the form is complete I want a button on the parent component to see if the form was complete before submitting it. 为了澄清起见,子组件是要填写的表单。表单完成后,我希望父组件上的按钮可以在提交之前查看表单是否完成。

This was achieved simply by interacting with the child component using a template reference variable . 这可以通过使用模板引用变量与子组件进行交互来简单地实现。

Add the variable to the child component selector element and access its properties and methods with it from the parent template: 将变量添加到子组件选择器元素,并从父模板使用它访问其属性和方法:

<child-selector #variable ></child-selector>
<button (click)="variable.ChildMethod()"/>

Alternatively, access the child component method/properties directly from component class: 或者,直接从组件类访问子组件方法/属性:

<button (click)="AccessChildMemebers(variable)"/>
AccessChildMemebers(elem){
    elem.ChildMethod();
}

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

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