``` 组件交互,也就是让两个或多个组件之间共享信息的方法。 ``` ## 一、父组件向子组件传递数据。 >[info] 父组件通常使用属性型指令向子组件传递数据,子组件中需要引入Input模块,并定义属性用于接受传递的数据 1.子组件中 ``` import { Component, OnInit,Input } from '@angular/core'; //引入Input模块接受父组件传递的数据 @Input() name:string; //定义接受数据的变量 ``` 2.父组件中 ``` //父组件通过属性型绑定传递数据 [name] = "数据",[name] 是子组件中定义的接受数据的变量 <app-child [name]='"父组件的数据"'></app-child> ``` ## 二、父组件监听子组件的事件。 >[info] 使用EventEmitter实现自定义事件(子组件向父组件发射事件) 使用EventEmitter 来触发自定义事件,用于父子组件交互 1.子组件引入`EventEmitter`模块和`Onput`模块,`Onput`模块用于把`EventEmitter`的实例暴露出去 ``` import {Component,OnInit,EventEmitter,Output}from '@angular/core'; //引入EventEmitter模块,通过EventEmitter实现自定义事件 @Component({ selector: 'app-child', template: `<button (click)='clickfn()'>点击我触发自定义事件</button>` styleUrls: ['./child.component.css'] }) export class ChildComponent implements OnInit{ data: object = { 'msg': '测试', 'code': 1 }; //创建自定义事件对象 @Output() deleteRequest = new EventEmitter(); clickfn() { //触发自定义事件,并传递一些参数 this.deleteRequest.emit(this.data); } } ``` 2.父组件监听子组件的自定义事件,并绑定事件处理函数。 ``` // 监听子组件的自定义事件,并绑定事件处理函数 通过$event接受传递的参数 import { Component,OnInit,OnInit,ViewChild } from '@angular/core'; @Component({ selector: 'app-child', template: `<app-child (deleteRequest)='fn($event)'></app-child>` styleUrls: ['./child.component.css'] }) export class ParentComponent implements OnInit{ fn(data):void{ console.log(data) } } ``` ## 三、使用模板引用变量交互。 >[info] 在父组件模板里,使用模板引用变量代表子组件,利用引用变量读取子组件的属性和方法。 ``` // #child 使用模板引用变量代表子组件,可利于引用变量读取子组件的数据和调用子组件的方法 <app-child #child></app-child> // 通过模板引用变量读取子组件的数据 {{child.childData}} // 通过模板引用变量调用子组件的方法 <button (click)="child.childfn()">调用子组件的方法</button> ``` ## 四、父组件调用@ViewChild()。 >[info] 当父组件类内部需要这种访问子组件的属性和方法时,可以把子组件作为 ViewChild,注入到父组件里面。 ``` import { Component, OnInit,ViewChild } from '@angular/core'; //引入ViewChild模块 //定义子组件 ViewChild的参数是子组件本身,可使用模板引用变量代表子组件,或者引入子组件,传入子组件 @ViewChild("child") child; export class ParentComponent implements OnInit{ clickfn(){ console.log(this.child);//获取子组件 } } ``` ## 五、父组件和子组件通过服务来通讯 通过服务进行通讯本质是使用Rxjs存储数据,然后在组件中做数据共享。