I have a working code which injects any component via a service to the HTML:
ModalWindow.ts:
@Component({
selector: 'modal-window'
template: `
<div class="modal-dialog" role="document">
<div class="modal-content"><ng-content></ng-content></div>
</div>
`
})
export class ModalWindow {
}
Modalcontent.ts :
@Component({
selector: 'modal-content'
template: `
I'm beeing opened as modal!
`
})
export class ModalContent {
}
ModalService.ts :
/*1*/ @Injectable()
/*2*/ export class ModalService {
/*3*/
/*4*/ constructor(private _appRef: ApplicationRef, private _cfr: ComponentFactoryResolver, private _injector: Injector) {
/*5*/ }
/*6*/
/*7*/ open(content: any) {
/*8*/ const contentCmpFactory = this._cfr.resolveComponentFactory(content);
/*9*/ const windowCmpFactory = this._cfr.resolveComponentFactory(ModalWindow);
/*10*/
/*11*/ const contentCmpt = contentCmpFactory.create(this._injector);
/*12*/ const windowCmpt = windowCmpFactory.create(this._injector, [[contentCmpt.location.nativeElement]]);
/*13*/
/*14*/ document.querySelector('body').appendChild(windowCmpt.location.nativeElement);
/*15*/
/*16*/ this._appRef.attachView(contentCmpt.hostView);
/*17*/ this._appRef.attachView(windowCmpt.hostView);
/*18*/ }
/*19*/ }
App.ts:
@Component({
selector: 'my-app',
template: `
<button (click)="open()">Open modal window</button>
`,
})
Result (when click a button which calls this service method ) :
I already know what contentCmpFactory
and windowCmpFactory
are (lines #8,9)
But I don't udnerstnad what's going on later. Regarding lines #11,#12 - the docs says "creates a new component".
Questions :
1 - line #12 : What does [[contentCmpt.location.nativeElement]]
do ? (the docs says its type is projectableNodes?: any[][]
- What do they mean ??)
2 - line #14 : What does [[windowCmpt.location.nativeElement]]
do ?
3 - line #16,#17 : what and why do I need them if I already did appendChild
? (docs says : Attaches a view so that it will be dirty checked. - so ?).