-1

I have a function component as follows:

export class ChildComp {
   whoAmI() {
     return 'I am a child!!';
   }
}

My parent component:

import { ChildComp  } form './child.component';
export class ParentComp {
   constructor(private child: childComp  ) {}
   triggerChildFunction() {
      this.childComp.whoAmI();
   }
 }

The above method did not work for me. Can anyone please suggest me help?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
learner
  • 357
  • 1
  • 6
  • 16
  • Does this answer your question? [Call child component method from parent class - Angular](https://stackoverflow.com/questions/38974896/call-child-component-method-from-parent-class-angular) – Kamil Naja Apr 12 '20 at 22:44

2 Answers2

0

I think, that you child should be Angular service, not just class.

Injectable()
export class ChildService { // remember add this to module
   public whoAmI() {
     return 'I am a child!!';
   }
}

import { ChildService  } form './child.service';
export class ParentComp {
   constructor(private child: childService  ) {}
   triggerChildFunction() {
      this.childService.whoAmI();
   }
 }

You can also communicate two Angular components with Subject(), or use @ViewChild(). More informaction about @ViewChild you can find here

Kamil Naja
  • 6,267
  • 6
  • 33
  • 47
0

I guess it's the purpose of the concept of "Service".

my-service.service.ts

@Injectable()
export class MyService<T> {
  public stream$ = new Subject<T>();

  public getSteam$() {
    return this.stream$;
  }

  public publish(value: T) {
    this.stream$.next(value);
  }

}

child.component.ts

@Component()
export class ChildComponent<T> implements OnInit, OnDestroy {
  public whoami = 'child';

  private subscription: Subscription;

  constructor(
    private myService: MyService
  ) {}

  public ngOnInit() {
    this.subscription = this.myService.getStream$()
      .subscribe((value: T) => {
          this.functionToTrigger(value);
      });
  }

  public ngOnDestroy() {
    if(this.subscription) this.subscription.unsubscribe();
  }

  private functionToTrigger(arg: T) {
    // do your stuff
    console.log(JSON.stringify(arg))
  }
}

parent.component.ts

@Component()
export class ParentComponent<T> {
  public whoami = 'parent';

  constructor(
    private myService: MyService<T>
  ) {}

  public notifiyChild(value: T) {
    this.myService.publish(value);
  }
}