我是使用Angular2的新建筑指令。我想要的是创建一个弹出指令,用一些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 {
}
答案 0 :(得分:11)
另一个答案是相关但不同的。
对于更接近的内容,请参阅: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, Input, 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, WrapperDirective],
entryComponents: [WrapperContainerComponent]
})
export class MyModule{}
所以HTML最终是:
<some_tag *myWrapperDirective />
呈现为:
<my-wrapper-container>
<div class="whatever">
<some_tag />
</div>
</my-wrapper-container>
答案 1 :(得分:9)
您可以使用组件属性选择器和Angular 2内容投影<ng-content>
@Component({
selector: 'my-app',
template: `
<div class="app">
<div class="data" myWrapper>
<h2>Header</h2>
Content to be placed here.
</div>
</div>
`
})
export class AppComponent {}
@Component({
selector: '[myWrapper]',
template: `
<div class="my-class">
<div class="my-sub-class">
<ng-content></ng-content>
</div>
</div>
`
})
export class MyComponent {
}