Cara mendapatkan ng-template dengan properti @Input di Angular

Sep 26 2020

Saya mencoba membuat komponen yang harus ditemukan <ng-template>oleh properti @Input dan mengembalikannya konten.

Berikut adalah kode dari komponen ini.

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>

Dan berikut adalah contoh penggunaan komponen ini.

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

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

Masalahnya adalah bagaimana menemukan template tertentu dengan id itu.

Saya mencoba cara ini, tetapi tidak berhasil:

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

Saya juga mencoba mendapatkan semua templat dan kemudian menemukan yang spesifik dari daftar, tetapi itu juga tidak berhasil:

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

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

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

Adakah yang bisa membantu saya?

Jawaban

YuriBeliakov Oct 02 2020 at 19:40

Saya telah menemukan solusinya di sini: Dapatkan Template ViewChildren By Id

Saya telah membuat arahan sederhana dan kemudian menggunakannya untuk mendapatkan template berdasarkan 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;
}