TemplateRef in Angular 18 missing context

Discussão em 'Angular' iniciado por Aaron R, Novembro 27, 2024.

  1. Aaron R

    Aaron R Guest

    What am I missing here? The template seems to render but the context is empty, resulting in just an empty button being displayed. Written with Angular 18.

    import { AfterViewInit, Component, ElementRef, inject, TemplateRef, ViewContainerRef } from '@angular/core';

    @Component({
    selector: 'app-template-ref',
    standalone: true,
    imports: [],
    template:`
    <ng-container *ngTemplateOutlet="theTemplateReference; context: context">
    Template not rendered
    </ng-container>

    <ng-template #theActualTemplate let-templateTitle="title" let-action="someMethod">
    <h2>{{templateTitle}}</h2>
    <button (click)="action(templateTitle)"></button>
    </ng-template>
    `,
    styleUrl: './template-ref.component.scss'
    })
    export class TemplateRefComponent implements AfterViewInit {
    @Input({required: true}) theTemplateReference!: TemplateRef<ElementRef>;
    vcr = inject(ViewContainerRef);
    context = {
    title: 'templateRef Title',
    someMethod(title: string) {
    alert(`Alert for ${title}`);
    }
    }

    ngAfterViewInit() {
    console.log(this.theTemplateReference);
    this.vcr.createEmbeddedView(this.theTemplateReference);
    }

    }

    Continue reading...

Compartilhe esta Página