Angular 从入坑到挖坑 - 组件食用指南 (6)

子组件获取父组件数据

4.4.3、父组件获取子组件信息

使用 @ViewChild 装饰器获取

在子组件上定义一个模板引用变量

<h2>父组件内容:</h2> <h3>1、使用 @ViewChild 装饰器获取子组件数据</h3> <p> <button (click)="getChildMsg()">获取子组件的 msg 数据</button> </p> <p> <button (click)="runChildFunc()">调用子组件的方法</button> </p> <hr> <h2>子组件内容:</h2> <!-- 在子组件上定义一个模板引用变量 --> <app-child-component #childComponent></app-child-component>

在父组件中添加对于 ViewChild 的引用,然后使用 @ViewChild 装饰器来接收子组件的 dom 信息,从而获取到子组件的数据或方法

// 引入 ViewChild import { Component, OnInit, ViewChild } from '@angular/core'; @Component({ selector: 'app-parent-component', templateUrl: './parent-component.component.html', styleUrls: ['./parent-component.component.scss'] }) export class ParentComponentComponent implements OnInit { // 通过 @ViewChild 装饰器来接收字组件的 dom 信息 @ViewChild('childComponent') child: any; constructor() { } ngOnInit(): void { } getMsg() { alert('我是父组件的 getMsg 方法'); } getChildMsg() { alert(this.child.msg); } }

通过 @ViewChild 装饰器获取子组件数据

使用 @Output 装饰器配合 EventEmitter 实现

在子组件中引入 Output 和 EventEmitter,通过 @Output 装饰器定义一个事件触发器,然后就可以通过这个事件触发器的 emit 方法进行事件广播

// 引入 Output、EventEmitter import { Component, OnInit, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-child-component', templateUrl: './child-component.component.html', styleUrls: ['./child-component.component.scss'] }) export class ChildComponentComponent implements OnInit { public msg = 'child title'; // 定义一个事件触发器 @Output() childEmitter = new EventEmitter<string>(); constructor() { } ngOnInit(): void { } runParentFunc() { this.parentGetMsg(); } sendMsg() { this.childEmitter.emit(this.msg); } }

当子组件进行事件广播时,就可以通过在子组件上使用事件绑定的方式绑定到一个父组件事件,通过 $event 获取到子组件传递的数据值

<h2>父组件内容:</h2> <h3>2、使用 @Output 装饰器配合 EventEmitter 获取子组件数据</h3> <p>{{childMsg}}</p> <hr> <h2>子组件内容:</h2> <!-- 将子组件的事件广播绑定到父组件事件上 --> <app-child-component (childEmitter)='childEmitMsg($event)'></app-child-component> import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-parent-component', templateUrl: './parent-component.component.html', styleUrls: ['./parent-component.component.scss'] }) export class ParentComponentComponent implements OnInit { public childMsg: string; constructor() { } ngOnInit(): void { } childEmitMsg(event) { this.childMsg = event; } }

使用 @Output 装饰器获取子组件数据

4.4.4、非父子组件之间的通信

不管组件之间是否具有关联关系,都可以通过共享一个服务的方式来进行数据交互,也可以将需要进行共享的数据存储到一些存储介质中,通过直接读取这个存储介质中的数据进行通信

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpyfwf.html