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

73,136

Solution 1

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.

Solution 2

@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!
  }
}
Share:
73,136
Christophe Vidal
Author by

Christophe Vidal

Updated on January 17, 2020

Comments

  • Christophe Vidal
    Christophe Vidal over 4 years

    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?