2016-06-28 49 views
3

我用viewContainerRef.createComponent加载动态组件到根组件(.....),但实际其追加错了地方,Angular2 viewContainerRef.createComponent正常工作

enter image description here

我的代码:

----- ----- 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; 
      } 
     ); 
    } 
} 

回答

4

这是“按设计”。如果你想<custom-modal>里面<my-app>插入添加一个目标元素进入<my-app>模板,并以此作为目标又见讨论https://github.com/angular/angular/issues/9035

您需要从AppComponent传递到ModalService

@Component({ 
    selector: 'my-app', 
    template: `<div #target></div>` 
}) 
export class AppComponent { 
    @ViewChild('target', {read: ViewContainerRef}) viewContainerRef:ViewContainerRef; 

    constructor(private modalService:ModalService) {} 

    ngAfterViewInit() { 
    this.modalService.viewContainerRef = this.viewContainerRef; 
    } 
} 

这PR是有关类似的使用案例和您可能感兴趣的https://github.com/angular/angular/pull/9393

+0

THKS回复!我不熟悉stackoverflow。我不会在根组件中注入ModalService,我想知道我已经在ModalService中获得了ViewContainerRef,但为什么无法获得它的注入? – phevose

+0

我真的不明白你的问题。您从根组件获得'ViewContainerRef',并添加到它将创建'ViewContainerRef'的兄弟。如果你想在根元素中添加,你需要在根元素模板中的一个元素的'ViewContainerRef'。我的答案显示了如何获得这样的'ViewContainerRef'。 –

+0

换句话说,我可以从根的viewContainerRef服务中获取第一个孩子(my-app)ViewContainerRef吗?因为我不想污染根组件(除了设置this.viewContainerRef)。 – phevose