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

前端之家收集整理的这篇文章主要介绍了html – 在angular2中构建一个包装器指令(包装一些内容/组件)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是Angular2的新建筑指令.我想要的是创建一个popup指令,用于将内容与一些css类包装起来.

内容

内容可以是纯文本和标题,如:

  1. <div class="data">
  2. <h2>Header</h2>
  3. Content to be placed here.
  4. </div>

然后我想给它一个指令属性,如:popup

  1. <div class="data" popup>
  2. <h2>Header</h2>
  3. Content to be placed here.
  4. </div>

该指令应该做的是将div包装在里面,让我们说:

  1. <div class="some class">
  2. <div class="some other class">
  3. <div class="data">
  4. <h2>Header</h2>
  5. Content to be placed here.
  6. </div>
  7. </div>
  8. </div>

我到目前为止描述的情况,这是一个属性或结构指令.

  1. import { Directive,ElementRef,HostListener,Input } from '@angular/core';
  2.  
  3. @Directive({
  4. selector: `[popup]`
  5. })
  6.  
  7. export class PopupDirective {
  8.  
  9.  
  10. }

解决方法

另一个答案是相关但不同的.

对于更接近的事情,请参阅:How to conditionally wrap a div around ng-content – 我的解决方案适用于Angular 4,但链接的问题有一些关于Angular 2如何可行的提示.

我用组件和指令组合解决了这个问题.我的组件看起来像这样:

  1. import { Component,Input,TemplateRef } from '@angular/core';
  2.  
  3. @Component({
  4. selector: 'my-wrapper-container',template: `
  5. <div class="whatever">
  6. <ng-container *ngTemplateOutlet="template"></ng-container>
  7. </div>
  8. `
  9. })
  10. export class WrapperContainerComponent {
  11. @Input() template: TemplateRef<any>;
  12. }

我的指令是这样的:

  1. import { Directive,OnInit,TemplateRef,ComponentRef,ComponentFactoryResolver,ViewContainerRef } from '@angular/core';
  2.  
  3. @Directive({
  4. selector: '[myWrapperDirective]'
  5. })
  6. export class WrapperDirective implements OnInit {
  7.  
  8. private wrapperContainer: ComponentRef<WrapperContainerComponent>;
  9.  
  10. constructor(
  11. private templateRef: TemplateRef<any>,private viewContainerRef: ViewContainerRef,private componentFactoryResolver: ComponentFactoryResolver
  12. ) { }
  13.  
  14. ngOnInit() {
  15. const containerFactory = this.componentFactoryResolver.resolveComponentFactory(WrapperContainerComponent);
  16. this.wrapperContainer = this.viewContainerRef.createComponent(containerFactory);
  17. this.wrapperContainer.instance.template = this.templateRef;
  18. }
  19. }

为了能够动态加载组件,您需要将组件列为模块内的entryComponent

  1. @NgModule({
  2. imports: [CommonModule],declarations: [WrapperContainerComponent,WrapperDirective],exports: [WrapperContainerComponent,entryComponents: [WrapperContainerComponent]
  3. })
  4. export class MyModule{}

所以HTML到底是:

  1. <some_tag *myWrapperDirective />

其呈现为:

  1. <my-wrapper-container>
  2. <div class="whatever">
  3. <some_tag />
  4. </div>
  5. </my-wrapper-container>

猜你在找的HTML相关文章