Angular组件之间的通信方式无非是3种情况:
父传子、子传父、非父子传递
如下图所示:
1、首先准备相关环境:
1、创建Angular项目:ng new demo
2、查看是否启动成功:ng serve --open || ng serve --open port(4201...)
3、创建所需的component:
// 亦可简写 ng g c compoments/father...
ng generate compoment compoments/father
ng generate compoment compoments/firstSon
ng generate compoment compoments/secondSon
ng generate compoment compoments/other
4、在根组件里引用:<app-father></app-father>
2、父传子 @Input :可传数据、方法、整个组件
- 父组件定义要传入子组件的相关数据、方法、整个组件
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-father',
templateUrl: './father.component.html',
styleUrls: ['./father.component.css']
})
export class FatherComponent implements OnInit {
public msg: string = '我是父组件传过来的值'; // 传入子组件的数据
constructor() { }
ngOnInit(): void {
}
run() { // 传入子组件的方法
console.log('我是父组件的方法');
}
}
- 父组件调用子组件的时候传入数据
<p>我是父组件</p>
<!--
父组件调用子组件的时候传入数据、方法、整个组件
等价于赋值操作: [子组件变量]="父组件变量";
-->
<app-frist-son [msg]="msg" [run]='run' [home]='this'></app-frist-son>
- 子组件引入Input模块以及@Input 接收父组件传过来的数据、方法、整个组件
// 子组件引入Input模块
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-frist-son',
templateUrl: './frist-son.component.html',
styleUrls: ['./frist-son.component.css']
})
export class FristSonComponent implements OnInit {
@Input() msg: string; // 子组件中@Input接收父组件传过来的数据
@Input() run; // 子组件中@Input接收父组件传过来的方法
@Input() home; // 子组件中@Input接收父组件传过来的整个组件
constructor() { }
ngOnInit(): void {
console.log(this.msg);
this.run();
this.home.run();
}
}
- 父传子运行结果

3、子传父@Output、@ViewChild
…持续更新中,大家有什么好的建议请提出来,相互学习
4、非父子传递
1、公共的服务
2、Localstorage(大小约为5M)
3、Cookie
4、路由参数
5、rxjs中的Subject
接收值的页面:
import { Component, OnInit } from '@angular/core';
import { ReplaySubject } from 'rxjs'; // 引入ReplaySubject
export const toFather$ = new ReplaySubject<any>(); // 定义接口
@Component({
selector: 'app-father',
templateUrl: './father.component.html',
styleUrls: ['./father.component.css']
})
export class FatherComponent implements OnInit {
constructor() { }
ngOnInit(): void {
toFather$.subscribe(data => console.log(data)); // 接收home页面传入的值
}
}
传入值的页面:
import { toFather$ } from './../father/father.component';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
public data = 'This is a Subject Data!';
constructor() { }
ngOnInit(): void {
toFather$.next(this.data); // 传data值到father界面
}
}
根组件中的使用:
<app-home></app-home>
<app-father></app-father>
运行结果:

本文深入探讨Angular组件间通信的三种主要方式:父组件向子组件传递数据、子组件向父组件发送信息及非父子组件间的通信策略。文章通过实例演示了如何使用@Input和@Output装饰器实现父子组件间的数据交换,并介绍了利用公共服务、LocalStorage、Cookie、路由参数和RxJS的Subject进行非父子组件通信的方法。

1052

被折叠的 条评论
为什么被折叠?



