gpt4 book ai didi

angular - 如何在 Angular2 中渲染带有组件的动态模板

转载 作者:太空狗 更新时间:2023-10-29 17:05:15 24 4
gpt4 key购买 nike

我尝试了很多 stackoverflow 选项,比如 Load existing components dynamically Angular 2 Final Release .

我想要做的是获取带有 ajax 请求的 html 页面,并在我的自定义组件中呈现/编译此模板。

我发现 angular2 有两个已弃用的组件,我必须使用 ComponentFactoryResolver

在我的旧解决方案中,我可以设置一个“[innerHtml]”来呈现 HTML。现在我需要一个新的解决方案。

谁能帮帮我?

page.component.ts

import { Component, ViewChild, ViewContainerRef, ComponentFactory, OnInit, ComponentFactoryResolver } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';


@Component({
selector: "wd-page",
templateUrl: "/app/page/page.component.html",
providers: []
})
export class PageComponent implements OnInit {

// we need the viewcontainer ref, so explicitly define that, or we'll get back
// an element ref.
@ViewChild('dynamicChild', { read: ViewContainerRef })
private target: ViewContainerRef;

private page = {
Source: "<div><h2>Hello world</h2><one-of-my-components></one-of-my-components></div>"
}


constructor(
private vcRef: ViewContainerRef,
private resolver: ComponentFactoryResolver) { }


ngOnInit() {
//What code do i need here?
}
}
<div #dynamicChild></div>

<!-- Old implementation!

<div *ngIf="!showSource" [innerHTML]="page">
</div>
-->

最佳答案

问题已解决 感谢 Yurzui,

https://plnkr.co/edit/TAbupH4si62x10QZ7xuc?p=preview

来自不同帖子(Angular 2.1.0 create child component on the fly, dynamically)的通用 HTML outlete 可用于呈现其中包含自定义指令的模板。

不要忘记导入一个包含您要呈现的所有自定义组件的模块!

export function createComponentFactory(compiler: Compiler, metadata: Component): Promise<ComponentFactory<any>> {
const cmpClass = class DynamicComponent {};
const decoratedCmp = Component(metadata)(cmpClass);

// Import the module with required components here
@NgModule({ imports: [CommonModule, RouterModule, SharedModule], declarations: [decoratedCmp] })
class DynamicHtmlModule { }

return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
.then((moduleWithComponentFactory: ModuleWithComponentFactories<any>) => {
return moduleWithComponentFactory.componentFactories.find(x => x.componentType === decoratedCmp);
});
}

关于angular - 如何在 Angular2 中渲染带有组件的动态模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40092639/

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