Angular *ngIf not removing element even when condition becomes false DOM keeps adding...

Discussão em 'Angular' iniciado por Avinash Dalvi, Julho 29, 2025.

  1. I'm working on an Angular app (v14+), and I’m facing a strange issue with *ngIf inside a component.

    Inside my component template (post-card.component.html), I have this simple test markup:

    <span>{{ post.showComments }}</span>
    <span *ngIf="post.showComments">Amazing....!</span>


    Output : true Amazing....! Amazing....! Amazing....! Amazing....! Amazing....! Amazing....! Amazing....! Amazing....! Amazing....!

    post is an @Input() coming from the parent posts.component.ts like this:

    <app-post-card
    *ngFor="let post of posts; let i = index; trackBy: trackByPostId"
    [post]="post"
    [index]="i"
    [showComments]="post.showComments"
    ...
    ></app-post-card>


    In the parent, I toggle post.showComments using immutable update:

    this.posts = this.posts.map((p, i) => {
    if (i === index) {
    return { ...p, showComments: !p.showComments };
    }
    return p;
    });


    post.showComments is toggled correctly. I see the true/false value update inside the component.

    ngOnChanges() logs the expected value transitions.

    trackByPostId returns a stable and unique feedID string.

    Ensured trackBy is correct and returns unique, stable ID

    Verified that only one app-post-card is rendered per post (confirmed via logs)

    Used ng-template + ViewContainerRef with manual clear() and destroy()

    Logged ngOnInit and ngOnDestroy — component is not being re-instantiated

    Confirmed no DOM manipulation or animation libraries are modifying the view

    Expected behavior: When post.showComments becomes false, Angular should destroy the *ngIf block and remove the from DOM. But instead, the DOM keeps accumulating duplicates.

    Is there any scenario where *ngIf inside a child component doesn't destroy its view even though the input becomes false? Is Angular's view caching interfering due to deep nested components or incorrect diffing?

    Any ideas or debugging strategies to isolate this would be super helpful.

    Continue reading...

Compartilhe esta Página