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

Christophe Vidal picture Christophe Vidal · Jun 4, 2016 · Viewed 63.2k times · Source

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?

Answer

awiseman picture awiseman · Jun 5, 2016

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.