一.父子组件通信
1.父组件向子组件传值——@Input
2.子组件向父组件传值——@Output
1.父组件html文件
在父组件ts文件中定义好相关变量,在html文件中进行传入
<!-- 将动态内容抽离出子组件,转由父组件传入,从而加强了子组件的可重用性 -->
<app-scrollable-tab
[menus]="topMenus" # topMenus为父组件中定义的对象(数据)
(tabSelected)="handleTabSelected($event)" # 接收子组件的传值
></app-scrollable-tab>
<h1>这里是父组件</h1>
2.子组件ts文件
定义对应的变量进行接收
// 引入Input模块
import { Component, OnInit, Input, EventEmitter } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
// 接收父组件传入
@Input() menus: TopMenu[];
// 定义一个信号发射器,用来给父组件传递数据
@Output() tabSelected = new EventEmitter();
handleSelected(index: number){
this.selectIndex = index;
// 向外发送信息
this.tabSelected.emit(this.menus[this.selectIndex])
}
}
3.父组件主动获取子组件中的数据——@ViewChild
1.使用子组件时给子组件定义一个名称
<app-footer #footerChild></app-footer>
2.父组件中引入ViewChild并获取子组件对象
import { Component, OnInit ,ViewChild} from '@angular/core';
@ViewChild('footerChild') footer;
// 通过footer调用子组件中的变量和方法
this.footer.footerRun();
二.非父子组件通信
- 公共的服务
- Localstorage (推荐)
- Cookie
参考:https://www.bilibili.com/video/av59049211?from=search&seid=485997827014437418