Angular2 如何通过 ng-content 覆盖属性



我有一些代码看起来像

<ng-container>
<ng-content select="[content-body]"></ng-content>
</ng-container>

我需要覆盖 ng 内容中顶部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

最新更新