一、新建一个子组件

ng g component child

二、子组件中添加要被调用的方法

child.component.ts

export class ChildComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  greeting(name:string){
    console.log('hello'+name);
  }
}

三、主组件添加html代码

此处用2种方法呈现效果:

app.component.html

<!--1.在控制器里用typescript代码实现-->
<app-child #child1></app-child>

<!--2.在模板上用模板变量实现-->
<app-child #child2></app-child>
<button (click)="child2.greeting('Jerry')">按钮调用child2的greeting方法</button>

四、主组件控制器加相关调用

app.component.ts

export class AppComponent implements OnInit{

  @ViewChild('child1')
  child1:ChildComponent;

  ngOnInit(): void {
    this.child1.greeting('tom');
  }
  }

五、执行效果

这里写图片描述

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐