Aja
Aja

Reputation: 23

Invoke Child method(and pass data) from parent, Child will be dynamically loaded component(router-outlet or lazy loaded child) in angular

The child components are lazy loaded components so

<router-outlet #child >

parent

"child.childMethod()"

this is not working ,Could you please someone help me to call child method from parent component also how I can pass data from/to between child and parent component this will be like master layout and different child components scenario.

Upvotes: 0

Views: 578

Answers (1)

Rapha&#235;l Balet
Rapha&#235;l Balet

Reputation: 8573

From my understanding of angular, using child.childMethod() wont be possible when lazy loading a component that way, because the parent isn't aware of what it will load.

If you're trying to trigger the childMethod() multiple time, using a service may be an option.

It will be provided in the parent, which you'll then be able to use in the child one.

Then you may trigger the childMethod() by subscribing it to a provider from the parentService

// parent.module.ts
providers: [
  ParentService
]
// parent.service.ts
  triggerChildMethod$: BehaviorSubject<boolean> = new BehaviorSubject(null)
// parent.component.ts
constructor(private _parentService: ParentService) {}

childMethod() {
 this._parentService.next(true);
}
// child.component.ts
constructor(private _parentService: ParentService) {}

ngOnInit() {
 this._parentService
      .pipe(
        filter((event) => (typeof event === "boolean" ? true : false)), // Avoid triggered on instantiating
        takeUntil(this._unsubscribeAll), // Do not forget to unsubscribe
      )
      .subscribe((value) => {
         this.childMethod() // Here you are
      })
}

Upvotes: 0

Related Questions