我是Angular2的新建筑指令.我想要的是创建一个popup指令,用于将内容与一些css类包装起来.
<div class="data"> <h2>Header</h2> Content to be placed here. </div>
然后我想给它一个指令属性,如:popup
<div class="data" popup> <h2>Header</h2> Content to be placed here. </div>
该指令应该做的是将div包装在里面,让我们说:
<div class="some class"> <div class="some other class"> <div class="data"> <h2>Header</h2> Content to be placed here. </div> </div> </div>
我到目前为止描述的情况,这是一个属性或结构指令.
import { Directive,ElementRef,HostListener,Input } from '@angular/core'; @Directive({ selector: `[popup]` }) export class PopupDirective { }
解决方法
另一个答案是相关但不同的.
对于更接近的事情,请参阅:How to conditionally wrap a div around ng-content – 我的解决方案适用于Angular 4,但链接的问题有一些关于Angular 2如何可行的提示.
我用组件和指令组合解决了这个问题.我的组件看起来像这样:
import { Component,Input,TemplateRef } from '@angular/core'; @Component({ selector: 'my-wrapper-container',template: ` <div class="whatever"> <ng-container *ngTemplateOutlet="template"></ng-container> </div> ` }) export class WrapperContainerComponent { @Input() template: TemplateRef<any>; }
我的指令是这样的:
import { Directive,OnInit,TemplateRef,ComponentRef,ComponentFactoryResolver,ViewContainerRef } from '@angular/core'; @Directive({ selector: '[myWrapperDirective]' }) export class WrapperDirective implements OnInit { private wrapperContainer: ComponentRef<WrapperContainerComponent>; constructor( private templateRef: TemplateRef<any>,private viewContainerRef: ViewContainerRef,private componentFactoryResolver: ComponentFactoryResolver ) { } ngOnInit() { const containerFactory = this.componentFactoryResolver.resolveComponentFactory(WrapperContainerComponent); this.wrapperContainer = this.viewContainerRef.createComponent(containerFactory); this.wrapperContainer.instance.template = this.templateRef; } }
为了能够动态加载组件,您需要将组件列为模块内的entryComponent
:
@NgModule({ imports: [CommonModule],declarations: [WrapperContainerComponent,WrapperDirective],exports: [WrapperContainerComponent,entryComponents: [WrapperContainerComponent] }) export class MyModule{}
所以HTML到底是:
<some_tag *myWrapperDirective />
其呈现为:
<my-wrapper-container> <div class="whatever"> <some_tag /> </div> </my-wrapper-container>