加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:47:15 所属栏目:安全 来源:网络整理
导读:我有最简单的Angular结构指令: import { Directive,TemplateRef,ViewContainerRef } from '@angular/core';@Directive({ selector: '[hello]' })export class HelloDirective { constructor( private templateRef: TemplateRefany,private viewContainer: V
我有最简单的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>

我希望该指令能够为我做到这一点.我知道我可以使用Component范例并创建HelloComponent而不是HelloDirective,并使用ng-template等与@Component装饰器上的template或templateUrl属性定义的模板…但是有没有一种方法可以用于指令范式达到这样的结果?

解决方法

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

@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])
  }
}

您必须将MyComponent添加到@NgModule的entryComponents数组中

完整的示例可以在Stackblitz找到

也可以看看

> Creating a angular2 component with ng-content dynamically

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读