วิธีรับ ng-template โดย @Input property ใน Angular
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
ฉันพบวิธีแก้ปัญหาแล้วที่นี่: รับเทมเพลต ViewChildren ตาม Id
ฉันได้สร้างคำสั่งง่ายๆแล้วใช้เพื่อรับ template by 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;
}