我使用viewContainerRef.createComponent将动态组件加载到根组件(.....)中,但实际上它附加了错误的地方,
我的代码:
- - - - - - - - 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;
}
);
}
}
答案 0 :(得分:4)
这是"按照设计"。另见此讨论https://github.com/angular/angular/issues/9035
如果您希望在<custom-modal>
内插入<my-app>
,请将目标元素添加到<my-app>
的模板中,并将其用作目标。
您需要将其从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