Javascript 如何从角度上的父组件触发子组件的函数?

Javascript 如何从角度上的父组件触发子组件的函数?,javascript,angular,angular7,dom-events,angular-event-emitter,Javascript,Angular,Angular7,Dom Events,Angular Event Emitter,我有一个功能组件,如下所示: export class ChildComp { whoAmI() { return 'I am a child!!'; } } 我的父组件: import { ChildComp } form './child.component'; export class ParentComp { constructor(private child: childComp ) {} triggerChildFunction() {

我有一个功能组件,如下所示:

export class ChildComp {
   whoAmI() {
     return 'I am a child!!';
   }
}
我的父组件:

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

上述方法对我不起作用。有谁能建议我帮忙吗?

我认为,你们的孩子应该是有棱角的服务生,而不仅仅是班级

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();
   }
 }

还可以使用Subject()或使用@ViewChild()与两个角度组件进行通信。关于@ViewChild的更多信息,您可以找到

我想这就是“服务”概念的目的

我的服务.service.ts

@Injectable()
导出类MyService{
公共流$=新主题();
公共收入$(){
返回此.stream$;
}
公开发表(价值:T){
this.stream$.next(值);
}
}
子组件.ts

@Component()
导出类ChildComponent实现OnInit、OnDestroy{
公共whoami=‘儿童’;
私人认购:认购;
建造师(
私有myService:myService
) {}
公共ngOnInit(){
this.subscription=this.myService.getStream$()
.订阅((值:T)=>{
此函数为触发器(值);
});
}
公共恩格德斯特罗(){
如果(this.subscription)this.subscription.unsubscripte();
}
专用函数ToTrigger(arg:T){
//做你的事
log(JSON.stringify(arg))
}
}
parent.component.ts

@Component()
导出类ParentComponent{
公共whoami=‘家长’;
建造师(
私有myService:myService
) {}
公共呈报儿童(价值:T){
this.myService.publish(value);
}
}

他有模板还是只有方法?这是否回答了你的问题?