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

隐身守侯 提交于 2019-11-30 00:18:49
awiseman

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.

@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!
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!