我需要使用一个变量来制作我的 app.component.html 的 Selector Tag.
I need to make the Selector Tag of my app.component.html using a variable.
假设变量名是:componentVar:string
我需要我的 app.component.html:
I need my app.component.html:
<componentVar></componentVar>
或 <app-componentVar></app-componentVar>
您可以像这样在 ViewcontainerRef 中动态创建组件:
You can dynamically create your components within a ViewcontainerRef like this:
https://stackblitz.com/edit/angular-4asbmc
(不要忘记在你的应用模块的 entryComponents 中添加你想要动态注入到你的 dom 中的组件)
(Don't forget to add the components you want to dynamically inject in your dom in your app module's entryComponents)
一旦您能够插入组件,您应该能够管理哪些组件必须插入到您的条件中.
Once you are able to insert the components you shoud be able to manage which components have to be inserted into your with conditions.
编辑
您可以迭代一个可能如下所示的组件数组:
You can iterate on an array of component that could look like this:
let componentArray = [HeaderComponent, BannerComponent, FooterComponent];
然后遍历这个数组,调用将组件插入到视图容器引用中的方法.
and then iterate over this array calling the method that inserts your components in your viewcontainer reference.
createComponent(component) {
const factory = this.factoryResolver.resolveComponentFactory(component);
const componentRef = factory.create(yourViewContainerRef.parentInjector);
yourViewContainerRef.insert(componentRef.hostView);
}
虽然从你的应用组件 html 模板中调用你的组件会更容易,并且在你的模板中有这样的东西:
Though it would be musch easier to just call your components from your app component html template, and have something like this in your template:
<app-header *ngIf="yourConditions..."></app-header>
<app-banner *ngIf="otherConditions..."></app-banner>
<!-- and so on.... -->
这篇关于Angular 创建选择器标签 <app-component>使用变量或循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!