angular4中父组件如何调用子组件的方法

梦里梦外; 2022-05-26 04:17 193阅读 0赞

一、新建一个子组件

  1. ng g component child

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

child.component.ts

  1. export class ChildComponent implements OnInit {
  2. constructor() { }
  3. ngOnInit() {
  4. }
  5. greeting(name:string){
  6. console.log('hello'+name);
  7. }
  8. }

三、主组件添加html代码

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

app.component.html

  1. <!--1.在控制器里用typescript代码实现-->
  2. <app-child #child1></app-child>
  3. <!--2.在模板上用模板变量实现-->
  4. <app-child #child2></app-child>
  5. <button (click)="child2.greeting('Jerry')">按钮调用child2的greeting方法</button>

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

app.component.ts

  1. export class AppComponent implements OnInit{
  2. @ViewChild('child1')
  3. child1:ChildComponent;
  4. ngOnInit(): void {
  5. this.child1.greeting('tom');
  6. }
  7. }

五、执行效果

这里写图片描述

发表评论

表情:
评论列表 (有 0 条评论,193人围观)

还没有评论,来说两句吧...

相关阅读