gpt4 book ai didi

Angular2 viewContainerRef.createComponent 正常工作

转载 作者:太空狗 更新时间:2023-10-29 18:21:27 26 4
gpt4 key购买 nike

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

enter image description here

我的代码:

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

最佳答案

这是“按设计”的。另请参阅此讨论 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

关于Angular2 viewContainerRef.createComponent 正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38068413/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com