Я хочу создать динамические компоненты и вставить представления этих компонентов в контейнер.
Я думаю, что это может быть достигнуто ViewContainerRef.
Но я не знаю, можем ли мы получить ViewContainerRef
любого компонента? если да, то как?.
Я новичок в Angular, если есть какие-либо другие хорошие решения, доступные для обработки этого сценария, пожалуйста, предложите мне.
Обновление Я думаю, я довольно близко к решению. Ниже приведен код.
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() { }
}
Выход
<my-app>
<container>container</container><controlbox _ngcontent-lsn-3="">controlBox</controlbox>
</my-app>
Ожидаемый результат
<my-app>
<container>container
<controlbox _ngcontent-lsn-3="">controlBox</controlbox>
</container>
</my-app>