另一个答案是相关但不同的。
如需更详细的信息,请参阅: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>