Angular2 viewContainerRef.createComponent work correctly

若如初见. 提交于 2019-12-10 10:29:03

问题


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

my code:

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

回答1:


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.

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

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



来源:https://stackoverflow.com/questions/38068413/angular2-viewcontainerref-createcomponent-work-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!