Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - How to trigger a method on a child from the parent

It's possible to send data from the parent to a child through @Input, or to call a method on the parent from the child with @Output, but I'd like to do exactly the other way around, which is calling a method on the child from the parent. Basically something like that:

@Component({   selector: 'parent',   directives: [Child],   template: ` <child   [fn]="parentFn" ></child> ` }) class Parent {   constructor() {     this.parentFn()   }   parentFn() {     console.log('Parent triggering')   } } 

and the child:

@Component({   selector: 'child',   template: `...` }) class Child {   @Input()   fn() {     console.log('triggered from the parent')   }    constructor() {} } 

Background is a kind of "get" request, i.e. for getting an up-to-date status from the child.

Now I know I could achieve that with a service and Subject/Observable, but I was wondering whether there is not something more straightforward?

like image 256
Christophe Vidal Avatar asked Jun 04 '16 21:06

Christophe Vidal


People also ask

How do you send value from parent to child component?

Sending data to a child componentlinkThe @Input() decorator in a child component or directive signifies that the property can receive its value from its parent component. To use @Input() , you must configure the parent and child.


2 Answers

I think these might be what you're looking for:

https://angular.io/guide/component-interaction#parent-interacts-with-child-via-local-variable

https://angular.io/guide/component-interaction#parent-calls-an-viewchild

You can access child properties and methods using local variables within the template or using the @ViewChild decorator in the parent's component class.

like image 79
awiseman Avatar answered Oct 04 '22 13:10

awiseman


@ViewChild is the right solution, but the documentation linked above was a bit unclear for me, so I pass a bit more friendly explanation which helped me to understand it.

Let's have a ChildComponent with a method:

whoAmI() {   return 'I am a child!!'; } 

And the parent component, where we can call method above by using '@ViewChild` technique:

import { Component, ViewChild, OnInit } from '@angular/core';  import { ChildComponent } from './child.component';  @Component({   selector: 'app-root',   templateUrl: './app.component.html',   styleUrls: ['./app.component.css'] })  export class AppComponent implements OnInit {    @ViewChild(ChildComponent) child: ChildComponent;    ngOnInit() {     console.log(this.child.whoAmI()); // I am a child!   } } 
like image 39
mpro Avatar answered Oct 04 '22 13:10

mpro