Angular 组件通讯(@Input,@ViewChild)

为了演示【父子组件通讯】,我们首先通过CLI 创建两个组件分别扮演父子组件(相对),分别是【parent】和 【child】:

//父子组件相对,这里方便演示组件直接取名【parent】和【child】
ng generate component components/parent
ng generate component components/child

1.在组件【parent】中挂载子组件【child】,【parent.component.html】

<app-child></app-child>

查看子组件页面是否运行,然后我们开始针对以下环节构建对应的代码;

父组件给子组件通讯

  1. 子组件可以获取父组件的数据;
  2. 子组件可以执行父组件的方法;

继续上面的步骤,在父组件【parent】的【parent.component.ts】中构建一个字符串字段和一个方法,代码如下:

//1.在class类中构建字段
public parentData:string = '我是parentData数据';

//2.在class类中构建方法
runParent():void{
    console.log('我是Parent方法');
}

接下来我们再改造父组件【parent.component.html】页面中挂载的子组件【app-child】:

<!-- 挂载组件 -->
<app-child [parentData]="parentData" [runParent]="runParent" [parent]="this"></app-child> 

然后我们再把组件的【child.component.ts】文件中引入所需装饰器【@Input】,改造代码如下:

//1.引入装饰器【Input】
import { Component, OnInit, Input } from '@angular/core';

//2.在class类中接收父组件中的字段和方法
@Input() parentData:any; //接收父组件传的值
@Input() runParent:any; //接收父组件的方法
@Input() parent:any; //接收整个父组件

//3.在class类中创建子组件中的runChild方法
runChild():void{
    console.log('我是child方法');
    this.runParent();
}

最后我们在子组件【child.component.html】的页面中添加如下代码:

<h3>我是子组件</h3> <br/>
父传子 =》 {{domData}} <br/>
<button (click)="runChild()">调用父组件parent的方法</button>

运行如下所示:

注:其中 【app-child】中的 [parent]="this" 相对比较特殊,子组件可以获取整个父组件;

子组件给父组件通讯

  1. 父组件可以获取子组件的数据;
  2. 父组件可以获取子组件的方法;

父组件通过【@ViewChild】主动获取子组件的数据和方法;

  • 调用子组件给子组件定义一个名称,自定义名称【child】;
<!-- 挂载组件 -->
<app-child #child></app-child> 

<!-- #aside,ng中使用ViewChild获取dom -->
<aside #aside [ngClass]="{'aside': true}">
   我是侧边栏
</aside>
  • 子组件中定义字段和方法;
public childData:string = '获取childData数据';

run():void{
    console.log('我是子组件child的run()方法!');
}
  • 父组件ts中引入【ViewChild】并获取子组件的字段或方法;
//1.引入ViewChild 和 ElementRef
import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';

//2.获取子组件字段或方法
@ViewChild('child',{static:true}) child:any;

//ng推荐方式获取dom元素,页面【#aside】
@ViewChild('aside',{static:true}) aside:ElementRef;

//3.通过【ViewChild】获取子组件里面的方法和字段
getChildRun():void{
   console.log(this.aside.nativeElement.innerText); //ViewChild获取dom对象aside标签的文本
   this.child.run(); //调用子组件的方法
   console.log(this.child.childData); //获取子组件的字段
}

 注:【ViewChild】可以获取子组件的信息,同时还可以操作当前组件中的dom对象;

非父子组件通讯

  1. 组件之间传值;
  2. 共享方法;

非父子组件通讯,通常使用服务【service】或者BOM对象(浏览器对象)【Local Storage】对象间接的实现。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ChaITSimpleLove

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值