angular - 通过@Input构造组件选择器

标签 angular angular-components angular-template

如何在 Angular 中以编程方式构造选择器?

假设我有一个名为 header.component 的父组件,如下所示;

export class ContentHeaderComponent {
  @Input() iconName: string;
}

...我正在使用 Angular Feather 将图标添加到应用程序,这需要您执行以下操作来创建图标:

<i-chevron-down></i-chevron-down>

在我的 header 组件模板中,我想通过父组件将“chevron-down”传递给标签。实际上,我希望在 header 组件中执行类似的操作:

<i-{{ iconName }}></i-{{ iconName }}>

在 Angular 中可以即时构建选择器吗?

最佳答案

如果您使用基于CSS或连字的方法,您的用例将非常简单,但是因为您的库每个图标有1个comp,并且它们之间基本上没有通用接口(interface),据我所知有实际上没有办法将字符串映射到其对应的组件类。

评论中建议的方法不起作用,因为 Angular 不会从净化后的 HTML 创建组件实例

您可以尝试以下想法:您可以传递带有所需图标的模板并将其嵌入到组件中,而不是传递图标名称。这可以按如下方式完成:

@Component({
  selector: 'foo-header'
})
export class ContentHeaderComponent {
  @Input() iconTemplate: TemplateRef<any>;
}

content-header.component.html

<ng-container *ngIf="iconTemplate">
  <ng-container [ngTemplateOutlet]="iconTemplate"></ng-container>
</ng-container>

foo.component.html

<foo-header [iconTemplate]="iconRef"></foo-header>
<ng-template #iconRef>
  <i-chevron-down></i-foo-icon>
</ng-template>

另一种方法是直接嵌入图标标记到组件中:

@Component({
  selector: 'foo-header'
})
export class ContentHeaderComponent {}

content-header.component.html

<ng-content select="[header-icon]"></ng-content>

foo.component.html

<foo-header>
  <i-chevron-down header-icon></i-foo-icon>
</foo-header>

您可以在 this article 中了解这些方法及其优缺点。 .

关于angular - 通过@Input构造组件选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54387701/

相关文章:

Angular 4 模板错误 : 'anonymous' does not contain such a member

angular - 模块构建失败。 TypeError : this. getResolve 不是函数

javascript - 开发nodeJS web应用是否需要express.js框架

html - 嵌套容器中的angular 4 flexbox垂直对齐和布局

css - Angular5 应用程序根据组件有条件地加载脚本和样式

angular - 如何通过单击事件将内容加载到另一个组件中? ( Angular 4)

javascript - 当宽度按百分比设置时如何检测 HTMLElement 调整大小

angularjs - 组件upperCaseComponent模板出错

angular - PrimgNg : <p-table> column sorting

javascript - ng-click ="currentTpl='/inventory.html'"内部 ng-repeat 不工作