Angular结构指令:使用另一个组件包装host元素

dhi*_*ilt 7 angular2-directives angular

我有最简单的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);
  }
}
Run Code Online (Sandbox Code Playgroud)

我用这种方式:

<div *hello>Hello Directive</div>
Run Code Online (Sandbox Code Playgroud)

它按预期显示"Hello Directive"消息.现在我想通过用另一个组件包装来更改内容:

<my-component>Hello Directive</my-component>
Run Code Online (Sandbox Code Playgroud)

我希望该指令能够为我做到这一点.我知道我可以使用组件范例,HelloComponent而不是HelloDirective使用装饰器上的或ng-template由属性定义的模板来创建...但是有没有一种方法可以与指令范例一起使用来实现这样的结果?templatetemplateUrl@Component

yur*_*zui 10

您可以动态创建组件并将可投影节点传递给它.所以它看起来像

@Directive({ selector: '[hello]' })
export class HelloDirective {
  constructor(
      private templateRef: TemplateRef<any>,
      private viewContainer: ViewContainerRef,
      private resolver: ComponentFactoryResolver) {
  }

  ngOnInit() {
    const templateView = this.templateRef.createEmbeddedView({});
    const compFactory = this.resolver.resolveComponentFactory(MyComponent);
    this.viewContainer.createComponent(
      compFactory, null, this.viewContainer.injector, [templateView.rootNodes])
  }
}
Run Code Online (Sandbox Code Playgroud)

你要添加MyComponententryComponents阵列的@NgModule

完整的例子可以在Stackblitz找到

也可以看看

  • @MuratÇorlu 你的意思是 hello 组件没有得到输入吗?那是因为它的视图不是角度变化检测树的一部分。试试这个 https://stackblitz.com/edit/angular-jrtnmn?file=app/app.component.ts (2认同)