Angular动态模板加载可以使用Angular的TemplateRef和ViewContainerRef来实现。下面是一个示例代码,展示如何在Angular中动态加载模板:
import { Component, TemplateRef, ViewChild, ViewContainerRef } from '@angular/core';
@Component({
selector: 'app-dynamic-template',
template: `
`,
})
export class DynamicTemplateComponent {
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
@ViewChild('dynamicTemplate') dynamicTemplate: TemplateRef;
loadTemplate() {
this.container.clear();
this.container.createEmbeddedView(this.dynamicTemplate);
}
}
Dynamic Template
This is a dynamically loaded template.
在上面的示例代码中,我们在组件的模板中定义了一个ng-container元素作为容器,并引入了ViewContainerRef。我们还使用了ng-template标记需要动态加载的部分,并设置了一个模板引用变量dynamicTemplate。
在组件的loadTemplate方法中,我们首先清空容器内容,然后使用createEmbeddedView方法将动态模板加载到容器中。
通过这种方式,我们可以动态加载和替换模板内容,实现在Angular中的动态模板加载。
上一篇:Angular动态命名的出口
下一篇:Angular动态模板注入