查看: 38|回覆: 0

Angular组件——父组件调用子组件方法

[複製鏈接]

1

主題

0

回帖

0

積分

热心网友

金币
0
閲讀權限
220
精華
0
威望
0
贡献
0
在線時間
0 小時
註冊時間
2010-12-29
發表於 2020-8-12 15:48:00 | 顯示全部樓層 |閲讀模式

viewChild装饰器。

父组件的模版和控制器里调用子组件的API。

1、创建一个子组件child1里面只有一个greeting方法供父组件调用。

复制代码
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-child1',
  templateUrl: './child1.component.html',
  styleUrls: ['./child1.component.css']
})
export class Child1Component implements OnInit {

  constructor() { }

  ngOnInit() {
  }

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

}
复制代码

2、父组件中分别在模版中用模版本地变量调用在控制器中用ts代码调用。

父组件写2个<app-child>并分别指定模版本地变量

<app-child1 #child1> </app-child1>
<app-child1 #child2> </app-child1>

3,在父组件控制器中声明一个由viewChild装饰器装饰的变量获得子组件的引用。

通过模版变量的名字child1找到相应的子组件并赋值给child1变量,拿到引用就可以调用子组件方法。

@ViewChild('child1')
child1:Child1Component; //父组件中获得子组件的引用

ngOnInit(){
  this.child1.greeting("Tom");
}

 

 

4,在父组件模版中调用子组件方法。

在父组件模版中加一个button,点击时去调用子组件child2的greeting方法。

<app-child1 #child1> </app-child1>
<app-child1 #child2> </app-child1>
<button (click)="child2.greeting('Jerry')">调用child2的greeting方法</button>

 



来源:https://www.cnblogs.com/telwanggs/p/13490970.html
回覆

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即注册

本版積分規則

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部