简体   繁体   English

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

[英]Angular2 how to override attributes via ng-content

I have some code that looks like 我有一些看起来像的代码

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

I need to override an attribute on the top div in the ng-content. 我需要在ng-content的顶层div上覆盖一个属性。 For example, if I need to add the html element attribute tabindex = "-1" via the container Component. 例如,如果我需要通过容器Component添加html元素属性tabindex = "-1"

<div content-body>
  Hello World
</div>

Needs to become 需要成为

<html>
  <div tabindex="-1">
    Hello World
  </div>
</html>

I don't want to have to update every <div content-body> in the codebase. 我不想更新代码库中的每个<div content-body> Any thoughts? 有什么想法吗?

There are two approaches I can think to assign attributes to projected content. 我可以考虑两种方法来为投影内容分配属性。

Approach 1: (Preferred IMO) Use directive for content selection, and put your business logic in that directive to assign attribute values to host. 方法1 :(首选IMO)使用指令进行内容选择,并将业务逻辑放入该指令中,以将属性值分配给主机。 For example: 例如:

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';
}

And use this directive to project your content as follows: 并使用此伪指令按以下方式投影您的内容:

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

Put your content in your component as follow: 将您的内容放在组件中,如下所示:

<app-product-items>
  <div appProductItemsContentBody>
    Hello World
  </div>

  <div appProductItemsContentBody *ngIf="showItem2">
    Item 2
  </div>
</app-product-items>

If you have more complexities and need to assign attributes based on some business logic in host component, then you can inject new service using dependency injection that will provide communication between directive and host component. 如果您有更多的复杂性,并且需要基于主机组件中的某些业务逻辑分配属性,则可以使用依赖项注入来注入新服务,该依赖项注入将提供指令和主机组件之间的通信。

Approach 2: Declare directive and use "@ContentChildren" or "@ContentChild" to find projected content and assign attributes directly. 方法2:声明指令,并使用“ @ContentChildren”或“ @ContentChild”查找投影内容并直接分配属性。

You can find out multiple content body items as follows: @ContentChildren(ProductItemsContentBodyDirective, { read: ElementRef }) contentBodyItems: QueryList; 您可以找到多个内容主体项,如下所示:@ContentChildren(ProductItemsContentBodyDirective,{阅读:ElementRef})contentBodyItems:QueryList;

Then, assign attributes using 'setStyle' and other methods on ElementRef. 然后,使用'setStyle'和ElementRef上的其他方法分配属性。

Hope this helps. 希望这可以帮助。

See example at: https://stackblitz.com/edit/angular-ngcontent-attribute-assign 请参阅以下示例: https : //stackblitz.com/edit/angular-ngcontent-attribute-assign

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM