通过ngx引导模式函数将数据传递给子组件



我在角度应用程序的Parent组件中有以下代码

父组件

<div>
<button *ngIf="data.type == 'el'" (click)="readInfo('el')">click</button>
<button *ngIf="data.type == 'ga'" (click)="readInfo('ga')">click</button>
</div>

readInfo(type) {
if (type === 'el') {
this.bsModalRef = this.modalService.show(ChildComponent, { class: 'modal-lg' }, el);
} else if (type === 'ga') {
this.bsModalRef = this.modalService.show(ChildComponent, { class: 'modal-lg' }, ga);
}
}

儿童组件

<div class="container" *ngIf="el">
<!-- el contents goes here -->
</div>
<div class="container" *ngIf="ga">
<!-- ga contents goes here -->
</div>

我想通过模态函数将一个值从父组件传递给ChildComponent。我的目标是在我的ChildComponent中检索这个值,并使用*ngIf 显示基于它的内容

解决方案1

使用回调将数据传递回父组件,并通过组件属性将数据传递给子组件。

this.modalSvc.show(LoadGeneratorAddModalComponent, {
initialState: {
successCb: (data) => {
// data come from the modal, assign it to your variable in parent component
this.dataPassToChild = data;
}
}
}
); 

解决方案2

您总是可以通过服务传递数据,创建主题,并在服务中公开可观察的内容。您可以在子组件中观察可观察到的,并在模态组件中触发事件。

最新更新