首页 > 解决方案 > 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>代码库中的每一个。有什么想法吗?

标签: javascriptangular

解决方案


我可以考虑两种方法来为投影内容分配属性。

方法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


推荐阅读