angularionic-frameworkangular2-ngcontent

Use <ng-content> to pass HTML from parent component and display in a modal component


I have a modal component in which is getting used in different modules. To make it dynamic, I need to pass design from a parent component from where I am calling the modal.

I tried to use ng-content to pass the design but since its a modal component, I am not sure how to pass the HTML and how it will get display in modal.

Calling modal from component

 const modal = await this.modalController.create({
      component: AutoCompleteModalComponent,
      cssClass: 'fullpage-modal',
    });
   
    return await modal.present();

The end goal is to insert the HTML (for example,<p>Hello</p>) in a parent component from where I am calling the modal, and that HTML should get displayed in modal. I am hoping this can be done with ng-content or ng-templateoutlet. Please help me in this.


Solution

  • I've no experience with ionic, but you can try the following.

    In the parent component template, add a ng-template with the content to project.

    <ng-template #myModalContent>
      <p>Hello</p>
    </ng-template>
    

    Grab the reference to this template with viewChild and pass it as a componentProp

    class ParentComponent {
      @ViewChild('myModalContent') modalContent: TemplateRef;
    
      ...
    
      yourOpenModalMethod(){
        const modal = await this.modalController.create({
          component: AutoCompleteModalComponent,
          cssClass: 'fullpage-modal',
          componentProps: {
            projectedContent: this.modalContent
          }
        });
    
        return await modal.present();
      }
    }
    

    Define an Input in the modalComponent to grab the prop.

    class AutoCompleteModalComponent {
      @Input() projectedContent: TemplateRef;
      
      ...
    }
    

    And finally in the modal template add a ng-container to render the template

    <ng-container [ngTemplateOutlet]="projectedContent"></ng-container>