Skip to content

ng-template gets rendered twice during hydration (when anchor comment node is not projected) #50543

Closed

Description

@michael-hein

Which @angular/* package(s) are the source of the bug?

platform-browser

Is this a regression?

No

Description

when hydration is enabled and a component uses ngTemplateOutlet to render a template passed from a parent e.g. via ContentChild then its getting rendered twice for the duration of the hydration.

So it looks the like this if 'abc' is the template content
received from server
abc

during hydration
abc abc <-- this looks sometimes a bit ugly

after hydration
abc

So is it possible that the passed template gets just once rendered during the hydration process?

The relevant code parts for reprodruction:

<app-shell>
  <ng-template #customTemplate>
    <p>template</p>
  </ng-template>
</app-shell>
@Component({
  selector: 'app-shell',
  template: `<ng-container
    *ngIf="customTemplate"
    [ngTemplateOutlet]="customTemplate"
  ></ng-container>`,
  styles: [],
})
export class ShellComponent {
  @ContentChild('customTemplate', { static: true })
  customTemplate: TemplateRef<any> | null = null;
}

Please provide a link to a minimal reproduction of the bug

https://github.com/michael-hein/hydration-ng-template

Please provide the exception or error you saw

N/A

Please provide the environment you discovered this bug in (run ng version)

Angular CLI: 16.0.4        
Node: 18.16.0
Package Manager: npm 8.19.3
OS: win32 x64

Angular: 16.0.4
... animations, cli, common, compiler, compiler-cli, core, forms
... platform-browser, platform-browser-dynamic, platform-server
... router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1600.4
@angular-devkit/build-angular   16.0.4
@angular-devkit/core            16.0.4
@angular-devkit/schematics      16.0.4
@nguniversal/builders           16.0.2
@nguniversal/express-engine     16.0.2
@schematics/angular             16.0.4
rxjs                            7.8.1
typescript                      4.9.5

Anything else?

No response

Activity

  1. added
    area: core
    on Jun 1, 2023
  2. modified the milestone: needsTriage on Jun 1, 2023
  3. dylhunn commented on Jun 1, 2023

    @dylhunn
    Contributor

    (@jessicajaniuk and @AndrewKushnir for visibility.)

  4. added
    P4
    on Jun 1, 2023
  5. modified the milestones: needsTriage, Backlog on Jun 1, 2023
  6. AndrewKushnir commented on Jun 1, 2023

    @AndrewKushnir
    Contributor

    @michael-hein thanks for reporting the issue and providing a repro, this is very helpful.

    I've performed the investigation and found out that what happens is that new nodes are being created for the template instead of reusing existing ones (hence, the duplication), but since you have the setTimeout in the code, it delays the time when hydration kicks off the cleanup operation (is depends on the ApplicationRef.isStable). As a result, the cleanup operation happens a bit later, thus leaving duplicated content visible. During the cleanup run, the SSR'ed content gets removed, since it was not claimed.

    I further looked into why existing nodes were not picked up by the hydration and found out that the "anchor" comment node for the projected <ng-template> is considered "disconnected" from the DOM (thus hydration can not find it) and that results in the "regular rendering" codepath. In fact, the "anchor" comment node is really disconnected from the DOM tree, since there was no <ng-content> tag present in the ShellComponent component template. This is not a problem in a simple case, but for more complex scenarios and for hydration purposes, that "anchor" node should be present in live DOM.

    To fix the problem, you can add the <ng-content /> tag to the ShellComponent component template. In this case, the comment node would be content-projected (added to the live DOM) and hydration will pick it up.

    (adding P4 priority for now and leaving this ticket open to discuss further with the team whether we need to improve this behavior)

  7. changed the title [-]ng-template gets rendered twice during hydration[/-] [+]ng-template gets rendered twice during hydration (when anchor comment node is not projected)[/+] on Jun 1, 2023
  8. michael-hein commented on Jun 2, 2023

    @michael-hein
    Author

    thanks for the fast response and for looking into it. I really appreciate it :)

    Yes the setTimeout was only to better see it, that was rendered twice.

    With the <ng-content /> tag it works perfectly. Thank you!

    <app-shell>
        <ng-template #customTemplate>
          <p>template</p>
        </ng-template>
      </app-shell>
    
    @Component({
      selector: 'app-shell',
      template: `<ng-content /><ng-container
          *ngIf="customTemplate"
          [ngTemplateOutlet]="customTemplate"
        ></ng-container>`,
      styles: [],
    })
    export class ShellComponent {
      @ContentChild('customTemplate', { static: true })
      customTemplate: TemplateRef<any> | null = null;
    }
    
  9. CarlosTorrecillas commented on Jun 19, 2023

    @CarlosTorrecillas

    @AndrewKushnir I have tried the <ng-content /> without success. Perhaps I am not doing something wrong. In my scenario I have

    <ng-template #template>
        <ng-container *ngIf="googleBusiness">
            <li>
                Google Business info 1
            </li>
            <li>
                Google Business info 2
            </li>
        </ng-container>
    </ng-template>
    

    And my component looks like:

    export class GoogleBusinessComponent implements OnInit {
        @Input() googleBusiness: IGoogleBusiness;
        @ViewChild('template', { static: true }) template: TemplateRef<unknown>;
    
        constructor(private viewContainerRef: ViewContainerRef) { }
          
        ngOnInit() {
            this.viewContainerRef.createEmbeddedView(this.template);
            this.viewContainerRef.element.nativeElement.remove();
        }
    }
    

    Essentially I want to remove the component tag from being rendered since that component adds two

  10. items to an existing list. I have added the <ng-content /> tag inside the ng-template, and outside. Do I have to do anything else to prevent the component being rendered twice?

  • AndrewKushnir commented on Jun 19, 2023

    @AndrewKushnir
    Contributor

    @CarlosTorrecillas the problem that you describe might be different from the one reported here. Could you please try to update your app to v16.1.1 (most recent at this moment) and test the behavior once again? If the problem still exists, please create a minimal repro (in a form of a GitHub repository with a new ng new app) and submit a new ticket, we'll take a look. Thank you.

  • 14 remaining items

  • jwittekind commented on Dec 6, 2024

    @jwittekind

    +1 I also experience this issue with <ng-content/>, <ng-template/> or custom templateRefs using @ContentChild.
    Please fix this issue

  • tsteuwer-accesso commented on Apr 30, 2025

    @tsteuwer-accesso

    We are building a large ecommerce application using PrimeNG as well and are now running into this issue when we're using <ng-template />. Is there any plans from the Angular team to address this anytime soon? It's been almost 2 years.

  • artakvzn commented on May 6, 2025

    @artakvzn

    Is there any update or planned milestone for improving hydration behavior in these scenarios? This issue affects some common patterns in SSR-heavy apps where conditional rendering is handled within ng-template.

  • added 3 commits that reference this issue on Jun 10, 2025
    29b43ff
    2813f15
    fe58cb1
  • added a commit that references this issue on Jun 11, 2025
    2a45b55
  • added a commit that references this issue on Jun 12, 2025
    e343cdf
  • added a commit that references this issue on Jun 12, 2025
    8424b3b
  • thePunderWoman commented on Jun 12, 2025

    @thePunderWoman
    Contributor

    Hey everyone. We were able to figure out a fix for this and it will be released with the patch that goes out next week Wednesday. Thanks for your patience!

  • tsteuwer-accesso commented on Jun 12, 2025

    @tsteuwer-accesso

    Thank you @thePunderWoman !!!!

  • angular-automatic-lock-bot commented on Jul 13, 2025

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  • locked and limited conversation to collaborators on Jul 13, 2025
  • Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

    Metadata

    Metadata

    Labels

    P4area: corecore: hydrationstate: has PR

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions