Open a Modal Using an Option from a Dropdown - Angular 2 + ngx

泄露秘密 提交于 2021-02-10 11:58:25

问题


Using ngx-bootstrap (4) with Angular 2/CLI.

Trying to use a dropdown list to select which modal to open. The modal currently works fine if I just have a button for each modal (not a dropdown), but the requirements call for a dropdown.

I tried something like

<select class="detailsOption" (change)="openModal($event.target.value)">
   <option value="">Select Option</option>
   <option value={{modal1}} >Option 1</option>
   <option value={{modal2}}>Option 2</option>
</select>

<ng-template #modal1>
</ng-template

<ng-template #modal2>
</ng-template

openModal(template: TemplateRef<any>) {
  this.modalRef = this.modalService.show(template);
}

Obviously this example wouldn't work. But I was trying to find a way have the option values hold the template, and then when selected, would pass the template into openModal and then open the modal.

I did find this guys question but it had no answers and also he was using click events in a drop down which don't really trigger I believe. ngx-bootstrap calling a modal from a dropdown


回答1:


You can achieve this by opening the modal in the (change) event of the select

<select class="detailsOption" (change)="openModal($event.target.value)">
     <option value="">Select Option</option>
     <option value="modal1" >Option 1</option>
     <option value="modal2">Option 2</option>
</select>

<!-- Option 1 -->
<common-modal  #childModalOption1 [title]="'Option1 modal'"> 
    <div class="modal-body">Option 1 selected Modal </div>
</common-modal> 

<!-- Option 2 -->
<common-modal  #childModalOption2 [title]="'Option 2modal'"> 
    <div class="modal-body">Option 2 selected Modal </div>
</common-modal> 

You should be having multiple references of the modal-component by decorating them with @ViewChild decorator

@ViewChild('childModalOption1') childModalOption1 :CommonModalComponent;
@ViewChild('childModalOption2') childModalOption2 :CommonModalComponent;

Your openModal method should be as

openModal(event){
    if(event==='modal1'){
      this.childModalOption1.show()
      console.log(event)  
    } else if(event==='modal2'){
      this.childModalOption2.show()
    }
  }

LIVE DEMO



来源:https://stackoverflow.com/questions/48349426/open-a-modal-using-an-option-from-a-dropdown-angular-2-ngx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!