1

In my Angular app I have a component called Component1 with selector component-1, and it's template contains a nested instance of itself:

<div> <component-1></component-1> </div>

So the parent Component1 contains a child Component1.

My Goal:

Component1 contains a method method1(). I want to call the child component's method1 from the parent component. Something like this.child.method1().

What I've Tried:

In the component I get child with the following code: @ViewChild(Component1) child: Component1;. If I do console.log(this.child) I get an object that contains all the @Input and @Output values from Component1, but not the methods like method1().

What I Want To Know:

How do I access this.child.method1()?

RNdev
  • 953
  • 1
  • 8
  • 26

3 Answers3

1

I will suggest not trying to invoke the child method in the parent. Consider rethinking the architecture and the data flow of your app. You would want it to be the other way round, calling a method in the parent from a child using an event emitter to communicate https://angular.io/guide/component-interaction#parent-listens-for-child-event.

Parent Component:

export class ParentComponent implements OnInit {
    .....
    onExecute() {
        // Execute some code
    }
}

Child Component

@Component({
   selector: 'child-component',
   templateUrl: './child-component.component.html',
   styleUrls: ['./child-component.component.scss']
})
export class ChildComponent implements OnInit {
    @Output() execute = new EventEmitter();
    .....
    someMethod() {
        this.execute.emit(); // you can send any variable to parent
    }
}

When this.execute.emit(); is fired, your handler in your parent element (onExecute) will be called.

Here is a stackblitz demo

C.OG
  • 6,236
  • 3
  • 20
  • 38
0

I dont really get why you want to do that. Usually there is a necessity to call parent method from child, like closing a modal, etc. But check out this link https://stackoverflow.com/a/38974968/7393630. It might help what you want to do.

0

Are you tried with public methods in child component.

export class HelloComponent  {

  @Input() name: string;
  public method1() {
    console.log('yes It iss called');
  }

}

https://stackblitz.com/edit/angular-i55bbe