我有经由到HTML服务注入任何成分的工作代码:Angular - 服务注入动态组件?
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 。:
/*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>
`,
})
结果(点击一个按钮调用该服务的方法时):
我已经知道contentCmpFactory
和windowCmpFactory
是(行#8,9)
但是我不认为以后会发生什么。关于第#11,第12行 - 文档说“创建了一个新组件”。
问题:
1 - 线#12:什么是[[contentCmpt.location.nativeElement]]
办? (的文档说,它的类型是projectableNodes?: any[][]
- 这是什么意思?)
2 - 线#14:什么是[[windowCmpt.location.nativeElement]]
办?
3行#16,#17:如果我已经做了appendChild
,那么为什么需要它们? (docs说:附加一个视图,以便它会被检查脏。 - 所以?)。
♡♡一如既往....谢谢。多好的答案。 –
@yuruzi,但如果我有两个(名为'ng-content select = ...')ng内容,我该如何映射每个部分('header'到第一个ng-content,'body'到第二个ng-content)? https://plnkr.co/edit/ozjVRwM3VMzNVErbH92O?p=preview –
'[contentCmpt.location.nativeElement.children]'https://plnkr.co/edit/UnahRZEVa0diSxnKH3D8?p=preview – yurzui