So erhalten Sie ng-template über die @ Input-Eigenschaft in Angular

Sep 26 2020

Ich versuche, eine Komponente zu erstellen, die <ng-template>anhand der @ Input-Eigenschaft gefunden werden soll, und gebe den Inhalt zurück.

Hier ist der Code dieser Komponente.

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>

Und hier ist ein Beispiel für die Verwendung dieser Komponente.

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

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

Das Problem ist, wie man eine bestimmte Vorlage anhand ihrer ID findet.

Ich versuche es so, aber es funktioniert nicht:

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

Außerdem habe ich versucht, alle Vorlagen abzurufen und dann bestimmte aus der Liste zu finden, aber es funktioniert auch nicht:

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

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

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

Kann mir bitte jemand helfen?

Antworten

YuriBeliakov Oct 02 2020 at 19:40

Ich habe die Lösung hier gefunden: Get ViewChildren Template By Id

Ich habe eine einfache Direktive erstellt und verwende sie dann, um eine Vorlage anhand der ID abzurufen.

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;
}