Angularの@Inputプロパティでng-templateを取得する方法

Sep 26 2020

<ng-template>@Inputプロパティで検索してコンテンツを返すコンポーネントを作成しようとしています。

これがこのコンポーネントのコードです。

template.component.ts

import { Component, Input, TemplateRef,  ViewChild } from '@angular/core';

@Component({
  selector: 'my-template',
  templateUrl: './template.component.html'
})
export class TemplateComponent {
  @Input() id: string;

  templateRef: TemplateRef<any>;
}

template.component.html

<ng-container *ngIf="templateRef" [ngTemplateOutlet]="templateRef"></ng-container>

<ng-template id="1" #template1>
  <p>template 1 content</p>
</ng-template>

<ng-template id="2" #template2>
  <p>template 2</p>
</ng-template>

そして、これがこのコンポーネントの使用例です。

<h2>Template 1</h2>
<my-template id="template1"></my-template>

<h2>Template 2</h2>
<my-template id="template2"></my-template>

問題は、そのIDで特定のテンプレートを見つける方法です。

私はこの方法を試しましたが、機能しません:

@ViewChild(this.id, { static: true }) templateRef: TemplateRef<any>;

また、すべてのテンプレートを取得して、リストから特定のものを見つけようとしましたが、機能しません。

@ViewChildren(TemplateRef) templates: TemplateRef<any>[];

ngAfterViewInit() {
    this.templateRef = this.templates.find(template => template.name === id);
}

https://stackblitz.com/edit/angular-my-template-dynamic

誰か助けてもらえますか?

回答

YuriBeliakov Oct 02 2020 at 19:40

私はここで解決策を見つけました:IDでViewChildrenテンプレートを取得します

簡単なディレクティブを作成し、それを使用してIDでテンプレートを取得しました。

TemplateIdDirective

import { Directive, Input, TemplateRef } from '@angular/core';

@Directive({
  selector: 'ng-template[id]'
})
export class TemplateIdDirective {
  @Input() id: string;

  constructor(public template: TemplateRef<any>) { }
}

template.component.ts

@ViewChildren(TemplateIdDirective) private templates: QueryList<TemplateIdDirective>;

ngAfterViewInit() {
  this.templateRef = this.getTemplateRefById(this.templates, this.id);
}

getTemplateRefById(templates: QueryList<TemplateIdDirective>, id: string): TemplateRef<any> {
  const directive = templates.find(template => template.id === id);
  return directive ? directive.template : null;
}