简体   繁体   English

通过ngx bootstrap modal函数向子组件传递数据

[英]Passing data to the child component through ngx bootstrap modal function

I have the following code in my Parent component in an angular application我在角度应用程序的父组件中有以下代码

PARENT COMPONENT父组件

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

CHILD COMPONENT子组件

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

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

i want to pass a value to the ChildComponent from my parent component through the modal function.我想通过模态函数将值从我的父组件传递给 ChildComponent。 My objective is to retrieve this value inside my ChildComponent and display contents based on it using *ngIf我的目标是在我的 ChildComponent 中检索这个值并使用 *ngIf 显示基于它的内容

Solution 1解决方案1

Using callback to pass the data back to parent component, and pass it via component property to child component.使用回调将数据传递回父组件,并通过组件属性将其传递给子组件。

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

Solution 2解决方案2

You can always pass data via service, create a subject, and expose the observable in service.您始终可以通过服务传递数据、创建主题并在服务中公开可观察对象。 You can observe the observable in the child component, and trigger the event in the modal component.可以在子组件中观察observable,在模态组件中触发事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM