从指令中创建/获取TemplateRef

问题描述 投票:2回答:1

我正在尝试创建一个(结构)指令,该指令会插入TemplateRef,但在TemplateRef定义为“其他位置”。

上下文

我有时想在现有元素中插入任意内容into>],但是出于DOM的原因,不要将它作为组件(尽管类似属性的组件很好)很重要。

示例:

<table>
  <tr my-row-component></tr>
</table>
@Component({
  selector: 'tr[my-row-component]'
  template: `<td>...</td><td>...</td><td>...</td>...`
})

现在,我想做同样的事情,但是在表中插入2

行。所以我希望做类似的事情:
<table>
  <ng-template myTwoRowsDirective></ng-template>
</table>

问题是:

  • 我有一个结构指令,以便可以插入所需的代码
  • 我需要一个组件,以便可以编写要插入指令中的html。
  • 问题

如何在结构化指令中获取TemplateRef,但指令的调用者未传递该值?

@Directive({selector: '[myTwoRowsDirective]'})
export class MyTwoRowsDirective {
  constructor(
      viewContainerRef: ViewContainerRef) {
    const templateRef = ???; // Reference to template defined elswhere
    viewContainerRef.createEmbeddedView(templateRef, this.context);
  }
}

我正在尝试创建一个(结构性)指令,该指令将插入TemplateRef,但其中TemplateRef定义为“其他位置”。上下文我有时想在现有的内容中插入任意内容...

angular angular-material angular-directive angular-components
1个回答
0
投票

不知道这是否是推荐的做法,但这似乎可行(尽管未在您的用例上进行过测试:]

© www.soinside.com 2019 - 2024. All rights reserved.