Search code examples
angularangular2-templateangular-directiveangular2-directives

Angular custom structural directive fails to rebuild ViewContainer if template contains *ngIf


I have an issue with ViewContainers and Structural Directives.

I have a custom structural directive = eg “permissionAccess".

It selects data from my NGRX store and looks for matching permissions. If no permission it clears the ViewContainer. If it has permission it Rebuilds the ViewContainer using the injected TemplateRef. (This all works fine - I have tested with Dom elements, Components, Views)

But… it fails to rebuild the ViewContainer if any of the Dom contains "ngIf" directives.

Anyone know why this would happen?? I have no idea!

It even fails with the *ngIf=“true”

Template Example Works:

<div *cwbPermission=“'ADMIN'">
        <p>test container</p>
        <div>
          <p>Nested container1</p>
          <div>
            <p>Nested container2</p>
          </div>
        </div>
      </div>

Template Example Fails:

<div *cwbPermission=“'ADMIN'">
        <p>test container</p>
        <div *ngIf=“true">
          <p>Nested container1</p>
          <div>
            <p>Nested container2</p>
          </div>
        </div>
      </div>

Can anyone explain this to me?? I have no idea!


Solution

  • So, I am not sure if this the best approach to this issue but looks like it is working for me. I added a changeDetectorRef.detectChanges() after creating the template in the view container and the UI now updates as I expect. Not seen any issues so far.

     /**
      * Creates the template content
      */
      showContent(): void {
        this.viewContainer.remove();
        this.viewContainer.createEmbeddedView(this.templateRef, this.context, 0);
        this.cdref.detectChanges();
      }