Template Referencing not happening when origin has a *ngIf

52 Views Asked by At
<mat-icon
  #suggestionIcon="cdkOverlayOrigin"
  class="suggestionIcon" 
  *ngIf="part.highlight"
  (click)="openOverlay()"
  cdkOverlayOrigin
>
  add_circle
</mat-icon>
<ng-template 
  #myTemplate
  *ngIf="part.highlight"
  cdkConnectedOverlay 
  [cdkConnectedOverlayOrigin]="suggestionIcon"
> 
 overlay 
</ng-template>

I'm getting an error, saying

Property 'suggestionIcon' does not exist on type 'InteractionPostComponent'.ngtsc(2339) interaction-post.component.ts(38, 4): Error occurs in the template of component InteractionPostComponent.

click on this to see the code

I tried using [style.visible] instead if *ngIf, and it is working, but I want to know why *ngIf is not working

1

There are 1 best solutions below

0
On

According to the Template variable scope documentation, your suggestionIcon template reference is created when part.highlight is true. The scope can be explained in the code as below:

if (part.highlight) {
  let suggestionIcon = ...; // Create `suggestionIcon` variable within this scope
}

if (part.highlight) {
  // Access `suggestionIcon` is not possible as it does not exist
}

Thus, would suggest placing both <mat-icon> and <ng-template> elements under the root <ng-template>, to allow both elements can create and share the template reference variable as it is within the scope.

Also, for <ng-template>, you need to use [ngIf] (template input variable syntax) but not *ngIf expression. Reference: Angular ng-template, ng-container and ngTemplateOutlet - The Complete Guide To Angular Templates (The ng-template directive and ngIf section)

<ng-template [ngIf]="part.highlight">
    
  <mat-icon
    #suggestionIcon="cdkOverlayOrigin"
    class="suggestionIcon" 
    (click)="openOverlay()"
    cdkOverlayOrigin
  >
    add_circle
  </mat-icon>
  <ng-template 
    #myTemplate
    cdkConnectedOverlay 
    [cdkConnectedOverlayOrigin]="suggestionIcon"
  > 
    overlay 
  </ng-template>
    
</ng-template>

Demo @ StackBlitz