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