Cách lấy ng-template theo thuộc tính @Input trong Angular

Sep 26 2020

Tôi cố gắng tạo thành phần sẽ tìm thấy <ng-template>theo thuộc tính @Input và trả về nội dung của nó.

Đây là mã của thành phần này.

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>

Và đây là một ví dụ về việc sử dụng thành phần này.

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

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

Vấn đề là làm thế nào để tìm mẫu cụ thể theo id của nó.

Tôi thử theo cách này nhưng không hiệu quả:

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

Ngoài ra, tôi đã cố gắng lấy tất cả các mẫu và sau đó tìm cụ thể từ danh sách, nhưng nó cũng không hoạt động:

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

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

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

Có ai có thể giúp tôi không?

Trả lời

YuriBeliakov Oct 02 2020 at 19:40

Tôi đã tìm thấy giải pháp ở đây: Lấy mẫu ViewChildren theo Id

Tôi đã tạo một chỉ thị đơn giản và sau đó sử dụng nó để lấy mẫu theo 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;
}