javascript - 在 html 页面中通过 typescript 打印 html 标签
问题描述
这是一个角度应用程序。我想在另一个组件中调用一个组件。所以,如果我这样写第一个组件来使用第二个组件的选择器调用第二个组件:
html:
<div>
<app-nice-component></app-nice-component>
</div>
一切正常。
但是我有很多组件,如果我尝试从一个数组中做同样的事情,它不再是一个 HTML 标签,它变成一个字符串(我的第二个组件不再加载)
ts:
let x: string[] = [{<app-nice-component></app-nice-component>},{<app-nice2-component></app-nice2-component>}]
html:
<div>
{{x[0]}}
</div>
那么在第二种情况下,我怎样才能使它成为一个 HTML 标签,而不是一个字符串呢?
解决方案
我建议你阅读下一篇关于 Angular 中动态组件加载器的文档:https ://angular.io/guide/dynamic-component-loader
您需要动态加载组件。脚步:
创建一个指令来告诉您的 HTML 代码在哪里加载组件:
@Directive({ selector: '[myDirective]' }) export class MyDirective { constructor(public viewContainerRef: ViewContainerRef) { } }
使用新指令将您的 HTML 设置到 ng-template 中,不要忘记在使用它的模块中添加指令。
<div> Component loading: <ng-template myDirective></ng-template> </div>
创建一个动态加载的函数,需要导入所有你想使用的组件,在这个例子中我准备了3个组件并动态加载它们,你可以玩componentToLoad数组来动态加载更多或更少的组件。
ngOnInit() { let componentToLoad : any[]; componentToLoad = [ this.componentFactoryResolver.resolveComponentFactory(Component1Component), this.componentFactoryResolver.resolveComponentFactory(Component2Component), this.componentFactoryResolver.resolveComponentFactory(Component3Component) ] const viewContainerRef = this.myDirective.viewContainerRef; componentToLoad.forEach( c => { viewContainerRef.createComponent(c); }); }
推荐阅读
- checksum - 不同的校验和但相同的档案
- java - CommonsXsdSchemaCollection xsd 放入 Jar/War - Spring Boot WS
- python - 在python中解码错误的转义字符
- android - 如何在 android studio 中修复 loadURL webView?
- android - 当我只能访问文件名时,如何通过下载 url 访问 firebase 存储上的文件?
- python - 致命错误 C1083:无法打开包含文件:'io.h':没有这样的文件或目录
- javascript - React 可加载不渲染组件,仅显示加载功能
- spring - 模拟 Spring 的远程 JWT 服务
- html - 我想在页脚中分别超链接两个单词,没有文字装饰或下划线。有人知道 HTML 代码吗?
- react-native - 如果所有数据都在 ajax 请求或数据库中,请使用 redux