Search code examples
angularng-template

Access component inside on ng-template


I have a component inside of an ng-template. What is the best way to access it to call methods? I'm currently running into an issue where it is always undefined or unreachable with the normal methods I would have used to access it.

<ng-template #template>
<app-planned-expense-edit-form #editform
                               (save)="onPlannedItemSave($event)"
                               (isHidden)="onIsHidden($event)">

</app-planned-expense-edit-form>
</ng-template>

Solution

  • With , you can define template content that is only being rendered by Angular when you, whether directly or indirectly, specifically instruct it to do so, allowing you to have full control over how and when the content is displayed. I suggest using instead of using because the can be used to hold directives without creating an HTML element.

    and rewrite your code like this

    <ng-template #template [ngIf]="true">
    <app-planned-expense-edit-form #editform
                                   (save)="onPlannedItemSave($event)"
                                   (isHidden)="onIsHidden($event)">
    
    </app-planned-expense-edit-form>
    </ng-template>
    

    and if you want to access to these element in TS using @ViewChild with { static: true } configuration. The { static: true } option was introduced to support creating embedded views on the fly.