-->

Cannot import child component to parent component

2019-09-21 16:59发布

问题:

This question already has an answer here:

  • How to call another components function in angular2 7 answers

I am using Angular 5. I want to call the child component method from parent component. For this I am adding the import {myChildComponent} from './myChild/myChild.component'; //ERROR: Cannot find module ./myChild/myChild.component

How can I import the child component in any other component other than app.component.ts.(here it works)

回答1:

You can simply call function of child component from parent component using local variable in Angular.

For example

<hello name="{{ name }}" #childOne></hello>
<p (click)='childOne.callFromParent()'>
  Start editing to see some magic happen :)
</p>

here hello is child component.

Working Example

Second way

<hello name="{{ name }}" #childOne></hello>
<button (click)='callChildFunction()'>hello</button>

@ViewChild('childOne') childOne: any;

callChildFunction() {
    this.childOne.callFromParent();
  }