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

查看:211
本文介绍了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

如果要在<my-app>中插入<custom-modal>,请将目标元素添加到<my-app>的模板中,并将其用作目标.

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天全站免登陆