I want to create dynamic components and insert views of these components to a container.
I think this can be achieved by ViewContainerRef.
But I don't know, can we get ViewContainerRef
of any component? if yes then how?.
I am new to Angular, if there are any other good solutions available to handle this scenario, please suggest me.
Updated
I think, I am pretty much near to the solution. Below is the code.
app.component.ts
import {Component} from '@angular/core';
import {ContainerComponet} from './container.component'
@Component({
selector: 'my-app',
template: `
<container> </container>
`,
directives: [ContainerComponet]
})
export class AppComponent {
constructor() { }
}
container.component.ts
import {Component, ComponentResolver, ViewContainerRef} from '@angular/core'
import {controlBoxComponent as controlBox} from './controlBox.component';
@Component({
selector: 'container',
template: 'container'
})
export class ContainerComponet {
constructor(viewContainer: ViewContainerRef, private _cr: ComponentResolver) {
this._cr.resolveComponent(controlBox)
.then(cmpFactory => {
const ctxInjector = viewContainer.injector;
return viewContainer.createComponent(cmpFactory, 0, ctxInjector);
})
}
}
controlBox.component.ts
import {Component} from '@angular/core'
@Component({
selector: 'controlBox',
template: 'controlBox'
})
export class controlBoxComponent {
constructor() { }
}
Output
<my-app>
<container>container</container><controlbox _ngcontent-lsn-3="">controlBox</controlbox>
</my-app>
Expected Result
<my-app>
<container>container
<controlbox _ngcontent-lsn-3="">controlBox</controlbox>
</container>
</my-app>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…