0

My component A has a child component B. On start up, A shows up because of conditition in *ngIf. A uses an EmbeddedView show show image thumbnails. A also has a button which when clicked changes the condition of *ngIf and shows B (because B shows on some other condition of *ngIf). If a button in B is pressed then A shows back again.

A's html is something like

    <div *ngIf="this.tabType == this.questionTab" id="form-div-question" class="body__div--background"> 
    ....
    <ng-template #thumbnailTemplate let-context="context"> 
      <div id="{{context.divId}}"> 
        <button id="{{context.buttonId}}" type="button" data-toggle="modal" (click)="showEnlargeImage(context)">
          <img id="{{context.imgId}}" src="{{context.imgSrc}}"/> 
        </button>
        <a *ngIf="this.isEditing" href="javascript:void(0)" id="{{context.closeId}}" (click)="deleteThumbnailFromContainer(context)"></a> 
      </div>
    </ng-template>
...
  <div id="image-thumbnail-container">
    <ng-container #thumbnailContainer ></ng-container>
  </div>
    </div>

    <div *ngIf="this.tabType == this.submittedAnswerTab" id="form-div-submitted-answer" class="body__div--background">
      <b-component #bComponent [someInput]="..." (someEventFromB)="switchToQuestionTab($event)"></b-component>
    </div>

The EmbeddedView in A is access as follows

  @ViewChild("thumbnailContainer",{read:ViewContainerRef})
  thumbnailContainerRef:ViewContainerRef;

What I am noticing is that on start up A shows fine including its embedded view. Then B also shows when the button in A is clicked. But when the view switches back to A then the embedded view doesn't show up!! (rest of A shows up correctly). I tried to force recreating the embedded view, I get error that the reference to the container is not defined (i.e.thumbnailContainerRef is undefined).

I also notice that when B is shown, it seem to be initiated everytime but when A is shown, it is not reinitialised everytime (maybe because B is child and A is parent)

Why is the container reference becoming undefined?

Manu Chadha
  • 15,555
  • 19
  • 91
  • 184

1 Answers1

0

Taking inspiration from Angular 2 Show and Hide an element and What is the difference between *ngIf and [hidden]?

I seem to have solved the problem by using [hidden] instead of ngIf of A component.

<div [hidden]= "this.tabType != this.questionTab" ...>
</div>
<div *ngIf="this.tabType == this.submittedAnswerTab" id="form-div-submitted-answer" class="body__div--background">
      <b-component #bComponent [someInput]="..." (someEventFromB)="switchToQuestionTab($event)"></b-component>
    </div>

It seems that when '*ngIf' is false for A, Angular removes the embedded view and it doesn't get created again which seem to to be the reason why the ViewContainerRef is undefined when I switch back to A. Using [hidden] just hides A. Maybe there is code smell in my implementation but hey, I am still learning!

Manu Chadha
  • 15,555
  • 19
  • 91
  • 184