1

I'm developing Angular 2 + TypeScript app with modal dialogs.

I have main modal component:

<div class="modal">
    <div class="header">{{title}}</div>
    <div class="body">{{body}}</div>
    <div class="footer">{{footer}}</div>
</div>

where {{title}} - text, {{body}} and {{footer}} - html from different components.

And in component that contains button to open modal dialog I have this:

import { Component } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

import { ModalComponent } from './modal.component';
import { BodyOneComponent } from './body/body-one.component';
import { FooterOneComponent } from './footer/footer-one.component';

@Component({
    selector: 'ac-parent',
    templateUrl: './app/parent.component.html'
})
export class ParentComponent {
    constructor(private modalService: NgbModal) { }

    openModal() {
        const modalRef = this.modalService.open(ModalComponent);
        modalRef.componentInstance.title = "Modal title";
        modalRef.componentInstance.body = "get html from BodyOneComponent somehow";
        modalRef.componentInstance.footer = "get html from FooterOneComponent somehow";
    }
}

So, my problem is how can I get html content of component from other component? And how can I compile those html into one view? What is the best approach for doing that? Should I use something different from template expression?

A. Gladkiy
  • 3,134
  • 5
  • 38
  • 82

2 Answers2

0

model.ts seperate compo for

<div class="modal">
    <div class="header">{{title}}</div>
    <div class="body">{{body}}</div>
    <div class="footer">{{footer}}</div>
</div>

components is

import { Component, Input } from '@angular/core';

@Component({
  selector: 'model-app',
  template: '<h1>Model {{major}}</h1>',
})
export class ModelComponent  { 
@Input() major: number = 10;
name = 'Angular'; 

}

and parent compo passes value of major

import { Component, Output } from '@angular/core';

@Component({
  selector: 'my-app',
  template: '<h1>Hello {{name}}</h1> <model-app></model-app>',
})
export class AppComponent  { 

    name = 'Angular'; 
}
anshuVersatile
  • 2,030
  • 1
  • 11
  • 18
0

You can use ng-content. If you familiar with angular 1, it's similar to transclusion.

In your main modal, you can do something like this:-

<div class="modal">
    <div class="header">
       <ng-content select="[m-header]"></ng-content>
    </div>
    <div class="body">
       <ng-content select="[m-body]"></ng-content>
    </div>
    <div class="footer">
       <ng-content select="[m-footer]"></ng-content>
    </div>
</div>

Then in your parent component, you can use it like this:-

<h1>Hello {{name}}</h1> 
<modal>
    <div m-header>
       Your title here
    </div>
    <div m-body>
      <p>Your html content here</p>
    </div>
</modal>

Refer to details in my article here. https://scotch.io/tutorials/angular-2-transclusion-using-ng-content

Jecfish
  • 4,026
  • 1
  • 18
  • 16