angular借助父组件,实现兄弟组件的通讯

以父组件为中间件,将子组件A的值发射给父组件,父组件再传给子组件B。实现兄弟组件之间的通讯。

1、搭建测试demo,效果如图

                                        angular借助父组件,实现兄弟组件的通讯

2、在子组件A中@Output一个EventEmitter的实例“fashe”,再用这个“fashe”去调用emit 方法,将子组件A中的变量发射到父组件中。代码如下。

import { Component, Output ,EventEmitter,OnInit} from '@angular/core';
@Component({
selector: 'component-A',
templateUrl: './componentA.html',
styleUrls: ['./componentA.css']
})
export class componentA implements OnInit{
@Output() fashe = new EventEmitter();
dataA: string;
fasheA(){
this.dataA="我是来自A组件的数据";
this.fashe.emit(this.dataA);
}
ngOnInit(){
}
}

3、在父组件的HTML中的子组件A的标签中用“fashe”绑定一个事件

<div class="parent">
<h1>父组件</h1>
<h4>父组件接收:{{getDataFromA}}</h4>

<component-A (fashe)="getdataA($event)"></component-A>
<component-B [getDataFromParent]="getDataFromA"></component-B>


</div>

3、这是子组件A的HTML,用click事件来启动传递

<div class="component-A">
<h3>组件A</h3>
<button (click)="fasheA()">发射</button>
</div>

4、这是父组件的ts

import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
getDataFromA:string;
getdataA(event){
this.getDataFromA=event;
}
}

5、子组件B的HTML

<div class="component-B">
<h3>组件B</h3>
<h4>{{dataB}}</h4>
</div>

6、注意前方高能!!!关键是子组件B该怎么写,这里有个坑,我已开始就掉坑里了。

我已开始是这么写的,

import { Component, Input, OnInit } from '@angular/core';

@Component({
selector: 'component-B',
templateUrl: './componentB.html',
styleUrls: ['./componentB.css']
})
export class componentB implements OnInit {
@Input()getDataFromParent;

dataB: string;
constructor(){
this.dataB=this.getDataFromParent;
console.log('构造函数',this.dataB);
}

我们在浏览器中看下,

angular借助父组件,实现兄弟组件的通讯

居然是undefined   黑人问号.jpg??? 为什么父组件的值没传过来呢?难道我不该在构造函数中写,应该在ngOnInit中写?好,我们来试一下。

import { Component, Input, OnInit } from '@angular/core';

@Component({
selector: 'component-B',
templateUrl: './componentB.html',
styleUrls: ['./componentB.css']
})
export class componentB implements OnInit {
@Input()getDataFromParent;

dataB: string;
ngOnInit() {
this.dataB=this.getDataFromParent;
console.log('ngOnInit钩子',this.dataB);
}

在浏览器中查看,

angular借助父组件,实现兄弟组件的通讯

WTF?  难道我父组件中的值就传不过来了?

后来我师父让我这么写,问题就解决了呢!可我不知道为什么,查了半天资料也没查出来,如果又能能看到这文章,希望你来告诉我,以后如果我知道了,也会来评论区更新下。

import { Component, Input, OnInit } from '@angular/core';

@Component({
selector: 'component-B',
templateUrl: './componentB.html',
styleUrls: ['./componentB.css']
})
export class componentB implements OnInit {

dataB: string;
@Input() set getDataFromParent( getDataFromParent: string){
this.dataB = getDataFromParent;
console.log(this.dataB);
}
好,经过set之后,我们就能获取到来自父组件的值了。
angular借助父组件,实现兄弟组件的通讯angular借助父组件,实现兄弟组件的通讯就是这个问题啦,折腾了一上午,写出来,加深下印象。