【问题标题】:Render multiple templates inside a component template in Angular在 Angular 的组件模板中渲染多个模板
【发布时间】:2017-11-06 10:10:46
【问题描述】:

我正在尝试构建一个可以在两个模板之间进行拖动分区的组件。有点像复制两个相邻的可调整大小的框架。我在想我的组件将接受两个模板输入,然后在它们周围呈现一个 div 以及它们之间的一个 div 充当分区滑块。这是我认为实现的样子:

<template #frameOne>content of the first template</template>
<template #frameTwo>content of the second template</template>
<split-component [frameOne]="frameOne" [frameTwo]="frameTwo"><split-component>

组件选择器是“split-component”,模板的两个输入是“frameOne”和“frameTwo”。我在文档或任何示例中都找不到如何在组件模板中包含来自组件外部的模板。

这是我的起始组件:

import { Component, Input, TemplateRef, ViewContainerRef, OnInit } from '@angular/core';
@Component({
  selector: 'split-component',
  templateUrl: './split.component.html',
  styleUrls: ['./split.component.scss']
})
export class SplitComponent implements OnInit {
  @Input() firstFrame: TemplateRef<any>;
  @Input() secondFrame: TemplateRef<any>;
}

以及它的模板:

<div class="split">
  <div class="frame1">{{firstFrame}}</div>
  <div class="divider-bar">
    <div class="handle">:::</div>
  </div>
  <div class="frame2">{{secondFrame}}</div>
</div>

当然 {{firstFrame}} 不起作用,但还有其他方法可以吗?

更新

我将此添加到我的组件中:

@ViewChild("frame1", {read: ViewContainerRef}) frame1: ViewContainerRef;
@ViewChild("frame2", {read: ViewContainerRef}) frame2: ViewContainerRef;

ngAfterViewInit(): void {
  this.frame1.createEmbeddedView(this.firstFrame);
  this.frame2.createEmbeddedView(this.secondFrame);
}

并将我的模板更改为:

<div class="split">
  <div class="frame1" #frame1></div>
  <div class="divider-bar">
    <div class="handle">:::</div>
  </div>
  <div class="frame2" #frame2></div>
</div>

但是它在框架div旁边而不是里面添加了模板的内容......

【问题讨论】:

  • 对此我不太确定,但正如您提到的,没有相同的文档,您可以检查动态组件。 angular.io/docs/ts/latest/cookbook/…
  • 是的,我现在可能已经阅读了该页面 10 次。文档严重缺乏。我认为我的解决方案还可以。我最终将框架包装在一个 div 中并使用它们来调整大小。
  • 您是否尝试过将ng-container 用作ViewContainerRef

标签: angular angular2-template angular2-directives


【解决方案1】:

我已经用我的解决方案更新了问题。渲染器也可能有一种方法可以做到这一点,但我已经停止了它的工作。我会对更优雅的解决方案感兴趣。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2013-06-16
    • 2018-05-20
    相关资源
    最近更新 更多