3
我用viewContainerRef.createComponent加载动态组件到根组件(.....),但实际其追加错了地方,Angular2 viewContainerRef.createComponent正常工作
我的代码:
----- ----- app.compoment.ts
export class AppComponent {
private viewContainerRef:ViewContainerRef;
public constructor(viewContainerRef:ViewContainerRef) {
this.viewContainerRef = viewContainerRef;
}
}
----- a.service.ts ------
@Injectable()
export class ModalService {
private viewContainerRef:ViewContainerRef;
constructor(applicationRef: ApplicationRef, injector: Injector,private compiler: ComponentResolver) {
var classOfRootComponent = applicationRef.componentTypes[0];
// this is an instance of application bootstrap component
var appInstance = injector.get(classOfRootComponent);
this.viewContainerRef= appInstance.viewContainerRef;
}
alert() {console.log(this.viewContainerRef);
this.compiler.resolveComponent(ModalComponent)
.then(
(factory) =>
this.viewContainerRef.createComponent(factory, 0, this.viewContainerRef.injector)
).then((componentRef) => {
return componentRef;
}
);
}
}
THKS回复!我不熟悉stackoverflow。我不会在根组件中注入ModalService,我想知道我已经在ModalService中获得了ViewContainerRef,但为什么无法获得它的注入? – phevose
我真的不明白你的问题。您从根组件获得'ViewContainerRef',并添加到它将创建'ViewContainerRef'的兄弟。如果你想在根元素中添加,你需要在根元素模板中的一个元素的'ViewContainerRef'。我的答案显示了如何获得这样的'ViewContainerRef'。 –
换句话说,我可以从根的viewContainerRef服务中获取第一个孩子(my-app)ViewContainerRef吗?因为我不想污染根组件(除了设置this.viewContainerRef)。 – phevose