有没有办法如何使用事件选择器在相同级别上的两个组件之间进行通信?
请参阅附带的html代码段中的评论。
<div class="custom-container">
<div class="row">
<div class="col-xs">
<app-entity-listing (associationShown)=" TO DO " [isFromRoot]="isFromRoot">
<!-- I am emiting a boolean value -->
</app-entity-listing>
</div>
<div class="col-xs-5">
<div class="right-column-wrapper">
<div class="main-container">
<app-create-entity-screen-no-association [isVisible]="true"></app-create-entity-screen-no-associatio
<! -- Based on emitted value from the first component, I will be visible or not -->
</div>
</div>
</div>
</div>
</div>
&#13;
答案 0 :(得分:0)
您可以创建父组件(PARENT),其中包含有关子组件(儿童B)可见性的信息。从另一个子组件(CHILD A),您可以使用EventEmitter更改可见性。见下图中的图片和代码。
import { Component, ViewChild, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<div style='background: red; padding: 10px; margin: 10px;'>
<app-parent></app-parent>
</div>
`,
})
export class AppComponent {
}
@Component({
selector: 'app-child-a',
template: `
<h3>CHILD A</h3>
<button (click)='changeVisibility(true)'>Show</button>
<button (click)='changeVisibility(false)'>Hide</button>
`,
})
export class ChildAComponent {
@Output() onVisibilityChanged = new EventEmitter<boolean>();
changeVisibility(visible: boolean) {
this.onVisibilityChanged.emit(visible);
}
}
@Component({
selector: 'app-child-b',
template: `
<h3>CHILD B</h3>
`,
})
export class ChildBComponent {
}
@Component({
selector: 'app-parent',
template: `
<h3>PARENT</h3>
<div style='background: green; padding: 10px; margin: 10px;'>
<app-child-a (onVisibilityChanged)='onVisibilityChanged($event)'></app-child-a>
</div>
<div *ngIf=visible style='background: blue; padding: 10px; margin: 10px;'>
<app-child-b></app-child-b>
</div>
`,
})
export class ParentComponent {
visible = false;
onVisibilityChanged(visible: boolean) {
this.visible = visible;
}
}