Angular 2 ng2-bootstrap modal inside child component called from parent component

前端 未结 1 750
不知归路
不知归路 2020-11-29 10:34

Hard to explain this. I had a simple working ng2-bootstrap modal example working. I expanded it to include Boostrap 4 Jumbotron example template for my home page, now the ng

1条回答
  •  无人及你
    2020-11-29 11:34

    Your common child modal component will be as below

    import {Component,Input, ViewChild} from '@angular/core';
    import { ModalDirective } from 'ng2-bootstrap/ng2-bootstrap';
    
    @Component({
      selector: 'common-modal',
      template: `
       
      `,
    })
    export class CommonModalComponent {
       @ViewChild('childModal') public childModal:ModalDirective;
       @Input() title:string;
      constructor() {
      }
      show(){
        this.childModal.show();
      }
      hide(){
        this.childModal.hide();
      }
    }
    

    Using the child component in your parent component will look as below

    import {Component, ViewChild, NgModule,ViewContainerRef} from '@angular/core'
    import { BrowserModule } from '@angular/platform-browser';
    import { ModalDirective,ModalModule } from 'ng2-bootstrap/ng2-bootstrap';
    import {CommonModalComponent} from './child.modal';
    @Component({
      selector: 'my-app',
      template: `
        
         
        
         
    
      `,
    })
    export class AppComponent {
      @ViewChild('childModal') childModal :CommonModalComponent;
      constructor(private viewContainerRef: ViewContainerRef) {
      }
    
    }
    

    Using the above code you can have a separate common modal dialog which can be reused, so that your header & footer remains the same and you can use Content-Projection to use change the body of the modal dialog.

    LIVE DEMO

    0 讨论(0)
提交回复
热议问题