我有最简单的 Angular 结构指令:
import { Directive, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({ selector: '[hello]' })
export class HelloDirective {
constructor(
private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {
this.viewContainer.createEmbeddedView(this.templateRef);
}
}
我这样使用它:
<div *hello>Hello Directive</div>
它按预期向我显示“Hello Directive”消息。现在我想通过用另一个组件包装它来更改内容:
<my-component>Hello Directive</my-component>
我希望指令为我做这件事。我知道我可以使用组件范例并创建HelloComponent
代替HelloDirective
并使用ng-template
等与定义的模板template
or templateUrl
财产在@Component
装饰器...但是有没有一种方法可以与指令范例一起使用来实现这样的结果?
您可以动态创建组件并向其传递可投影节点。所以它可能看起来像
@Directive({ selector: '[hello]' })
export class HelloDirective implements OnInit, DoCheck {
templateView: EmbeddedViewRef<any>;
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private resolver: ComponentFactoryResolver) {
}
ngOnInit() {
this.templateView = this.templateRef.createEmbeddedView({});
const compFactory = this.resolver.resolveComponentFactory(MyComponent);
this.viewContainer.createComponent(
compFactory, null, this.viewContainer.injector, [this.templateView.rootNodes])
}
ngDoCheck(): void {
if (this.templateView) {
this.templateView.detectChanges();
}
}
}
你必须添加MyComponent
to entryComponents
你的数组@NgModule
完整的示例可以在以下位置找到斯塔克闪电战 https://stackblitz.com/edit/angular-uhmyhe?file=app%2Fapp.module.ts
See also
- 动态创建带有 ng-content 的 angular2 组件 https://stackoverflow.com/questions/44284026/creating-a-angular2-component-with-ng-content-dynamically
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)