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

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

概述我是Angular2的新建筑指令.我想要的是创建一个popup指令,用于将内容与一些css类包装起来. 内容 内容可以是纯文本和标题,如: <div class="data"> <h2>Header</h2> Content to be placed here.</div> 然后我想给它一个指令属性,如:popup <div class="data" popup> <h2 我是Angular2的新建筑指令.我想要的是创建一个popup指令,用于将内容与一些CSS类包装起来.

内容

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

<div >    <h2>header</h2>    Content to be placed here.</div>

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

<div  popup>    <h2>header</h2>    Content to be placed here.</div>

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

<div >    <div >        <div >            <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 >  <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 >    <some_tag />  </div></my-wrapper-container>
总结

以上是内存溢出为你收集整理的html – 在angular2中构建一个包装器指令(包装一些内容/组件)全部内容,希望文章能够帮你解决html – 在angular2中构建一个包装器指令(包装一些内容/组件)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1106885.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-28
下一篇2022-05-28

发表评论

登录后才能评论

评论列表(0条)

    保存