微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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>

原文地址:https://www.jb51.cc/html/231862.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐