gpt4 book ai didi

Angular 2 同级组件之间的通信

转载 作者:太空狗 更新时间:2023-10-29 19:34:58 26 4
gpt4 key购买 nike

有什么方法可以使用事件发射器在同一级别 的两个组件之间进行通信吗?

请参阅随附的 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>

enter image description here

最佳答案

您可以创建包含有关子组件 (CHILD B) 可见性信息的父组件 (PARENT)。在另一个子组件 (CHILD A) 中,您可以使用 EventEmitter 更改可见性。请参见下面的图片和代码。

enter image description here

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;
}

}

关于Angular 2 同级组件之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41510044/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com