javascript - Angular2如何通过ng-content覆盖属性
问题描述
我有一些看起来像的代码
<ng-container>
<ng-content select="[content-body]"></ng-content>
</ng-container>
我需要覆盖 ng-content 中顶部 div 的属性。例如,如果我需要tabindex = "-1"
通过容器组件添加 html 元素属性。
<div content-body>
Hello World
</div>
需要成为
<html>
<div tabindex="-1">
Hello World
</div>
</html>
我不想更新<div content-body>
代码库中的每一个。有什么想法吗?
解决方案
我可以考虑两种方法来为投影内容分配属性。
方法1:(首选IMO)使用指令进行内容选择,并将您的业务逻辑放入该指令中以将属性值分配给主机。例如:
import { Directive, HostBinding } from '@angular/core';
@Directive({
selector: '[appProductItemsContentBody]'
})
export class ProductItemsContentBodyDirective {
@HostBinding('style.width') width = '200px';
@HostBinding('style.height') height = '200px';
@HostBinding('style.background-color') bgColor = 'yellow';
}
并使用此指令来投影您的内容,如下所示:
<ng-container>
<ng-content select="[appProductItemsContentBody]"></ng-content>
</ng-container>
将您的内容放入组件中,如下所示:
<app-product-items>
<div appProductItemsContentBody>
Hello World
</div>
<div appProductItemsContentBody *ngIf="showItem2">
Item 2
</div>
</app-product-items>
如果您有更多复杂性并且需要基于宿主组件中的某些业务逻辑分配属性,那么您可以使用依赖注入注入新服务,该服务将提供指令和宿主组件之间的通信。
方法2:声明指令并使用“@ContentChildren”或“@ContentChild”来查找投影内容并直接分配属性。
您可以找到多个内容正文项,如下所示: @ContentChildren(ProductItemsContentBodyDirective, { read: ElementRef }) contentBodyItems: QueryList;
然后,在 ElementRef 上使用“setStyle”和其他方法分配属性。
希望这可以帮助。
参见示例:https ://stackblitz.com/edit/angular-ngcontent-attribute-assign
推荐阅读
- d3.js - D3 js scaleTime 到不同年份的365~366天
- python - 如何在 Django Admin 中制作自定义错误消息
- docker - 如何在 Docker 中使用 Oracle 和 ActiveMQ 在 Tomcat 上部署 WAR 文件?
- c - 为什么 LLVM 会分配冗余变量?
- postgresql - 如何从两个 postgres DB 建立一对多映射
- mongodb - MongoDB - 嵌入,将一个集合插入另一个集合
- python - 确定一个字符串在 pandas DataFrame 中包含什么语言
- sql - 使用 Shell 脚本运行 SQL 查询并返回 CSV 格式的输出
- c# - 使用 OpenCL 在我的 GPU 上运行动态生成的代码是个好主意,还是有更好的方法?
- angular - Angular / Zone.js:正确拦截非角度 XMLHttpRequest-s?