有没有办法在运行时渲染 Angular 模板?

问题描述 投票:0回答:1

我正在使用

Angular 16.0.3
,我正在尝试制作一个接收模板字符串并在运行时渲染它的组件。模板字符串可以包含 Angular 组件,并且可能会从服务器获取。

我基于这个 StackOverflow 问题:在运行时渲染 Angular 字符串模板

我试过这个:

动态模板.component.ts

import { Component, Input, ViewChild, ViewContainerRef, ɵcompileComponent } from '@angular/core';

@Component({
selector: 'app-dynamic-template',
template: '\<ng-container #container\>\</ng-container\>'
})
export class DynamicTemplateComponent {
@Input() content: string
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef

constructor() {}

generate(): void {
const component = getComponentFromTemplate(this.content)
this.container.clear();
const componentRef = this.container.createComponent(component);
console.log(componentRef)
}
}

@Component({
template: '',
}) class TemplateComponent {
@ViewChild('heading') heading: HTMLHeadingElement
}

function getComponentFromTemplate(template: string) {
ɵcompileComponent(TemplateComponent, {
template,
standalone: true,
});

return TemplateComponent;
}

但我明白了:

控制台

JIT compilation failed for component class TemplateComponent {}
ERROR Error: The component 'TemplateComponent' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available.

JIT compilation is discouraged for production use-cases! Consider using AOT mode instead.
Alternatively, the JIT compiler should be loaded by bootstrapping using '@angular/platform-browser-dynamic' or '@angular/platform-server',
or manually provide the compiler with 'import "@angular/compiler";' before bootstrapping.
at getCompilerFacade (core.mjs:5088:15)
at TemplateComponent.get \[as ɵcmp\] (core.mjs:24683:34)
at getComponentDef (core.mjs:1839:16)
at ViewContainerRef.createComponent (core.mjs:23218:31)
at DynamicHtmlComponent.generate (dynamic-html.component.ts:16:41)
at GuestComponent.generate (guest.component.ts:16:27)
at GuestComponent_Template_button_click_3_listener (guest.component.html:3:20)
at executeListenerWithErrorHandling (core.mjs:15700:16)
at wrapListenerIn_markDirtyAndPreventDefault (core.mjs:15733:22)
at HTMLButtonElement.\<anonymous\> (platform-browser.mjs:666:17)

我的问题

  1. 我该如何解决这个问题?
  2. 有没有一种方法可以只让一个延迟加载的子模块使用 JIT 编译器,如果是,我该怎么做?
angular jit angular-template
1个回答
0
投票

在 angular.json 文件中,architect:build.options 下,添加/设置 "aot":false

根据各种文档,不建议在生产中使用。

© www.soinside.com 2019 - 2024. All rights reserved.