简体   繁体   中英

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.

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. 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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