你不能直接从字符串渲染这个模板,你需要先解析它,然后分别渲染每个组件。我建议使用其他格式来存储此信息,而不是简单的字符串(例如描述每个组件的 JSON,但它在很大程度上取决于您的用例),因为它可能更容易使用。
从 Angualar v13 开始,您可以使用 ViewContainerRef.createComponent 并直接传递 PrimeNG 组件引用。
每个 PrimeNG 可视化组件都会导出其模块和组件。例如,here您可以看到导出的模块中只有 ToolbarComponent 和 CommonModule),因此您不需要导入整个模块(如果您以编程方式渲染它,如下例所示),只需导入组件(这可能会有所不同)组件及其要求)。
这是创建 PrimeNG 工具栏 的简短示例,其中包含适合我的按钮(Angular 17.1.3、PrimeNG 17.6):
import { Toolbar } from 'primeng/toolbar';
import { Button } from 'primeng/button';
...
private viewRef = inject(ViewContainerRef);
private renderer = inject(Renderer2);
...
private renderToolbar() {
const parentElement = this.renderer.createElement('div');
const toolbar = this.viewRef.createComponent(Toolbar);
const toolbarGroupStart = this.renderer.createElement('div');
toolbarGroupStart.setAttribute('class', 'p-toolbar-group-start');
const toolbarMenuBtn = this.viewRef.createComponent(Button);
toolbarMenuBtn.instance.styleClass = 'p-button-info';
toolbarMenuBtn.instance.label = 'Menu';
toolbarGroupStart.appendChild(toolbarMenuBtn.instance.el.nativeElement);
toolbar.instance.getBlockableElement().appendChild(toolbarGroupStart);
parentElement.appendChild(toolbar.instance.getBlockableElement());
this.renderer.appendChild(document.body, parentElement);
}