html – 在angular2中构建一个包装器指令(包装一些内容/组件)

我是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>

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些