温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Angular中怎么通过父组件调用子组件

发布时间:2021-08-12 11:40:59 来源:亿速云 阅读:168 作者:Leah 栏目:web开发

本篇文章为大家展示了Angular中怎么通过父组件调用子组件,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

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

Angular中怎么通过父组件调用子组件

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

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

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

Angular中怎么通过父组件调用子组件

上述内容就是Angular中怎么通过父组件调用子组件,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI