Angular2 viewContainerRef.createComponent 工作正常 [英] Angular2 viewContainerRef.createComponent work correctly

查看:29
本文介绍了Angular2 viewContainerRef.createComponent 工作正常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 viewContainerRef.createComponent 将动态组件加载到根组件(.....) 中,但实际上它附加了错误的位置,

i used viewContainerRef.createComponent to load dynamic component into root component(.....) ,but actual it append the wrong place,

我的代码:

-----app.compoment.ts-----

-----app.compoment.ts-----

export class AppComponent { 
   private viewContainerRef:ViewContainerRef;
   public constructor(viewContainerRef:ViewContainerRef) {
    this.viewContainerRef = viewContainerRef;
  }
}

-----a.service.ts------

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

推荐答案

这是设计好的".另请参阅此讨论 https://github.com/angular/angular/issues/9035

This is "as designed". See also this discussion https://github.com/angular/angular/issues/9035

如果你想将 插入到 中,在 并将其用作目标.

If you want <custom-modal> to be inserted inside <my-app> add a target element into the template of <my-app> and use this as target.

你需要把它从 AppComponent 传递给 ModalService 就像

You need to pass it from the AppComponent to the ModalService like

@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/角度/角度/拉/9393

This PR is about a similar use case and might interest you https://github.com/angular/angular/pull/9393

这篇关于Angular2 viewContainerRef.createComponent 工作正常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆