簡體   English   中英

在Angular的組件模板中渲染多個模板

[英]Render multiple templates inside a component template in Angular

我正在嘗試構建一個可以在兩個模板之間創建拖動分區的組件。 有點像復制兩個相鄰的可調整大小的框架。 我在想我的組件將接受兩個模板輸入,然后在它們周圍渲染一個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的旁邊,而不是內部。

我已經用解決方案更新了問題。 也許也可以使用Renderer來做到這一點,但是我已經停止了工作。 我會對更合適的解決方案感興趣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM