Search code examples
angularangular-ng-if

How to remove old DOM content when *ngIf is triggered for the second time


I have an Angular 2 component that looks like this:

<div *ngIf="Data"> This is my data: {{Data}} </div>

Which outputs (Pretending that Data is just a string saying "Data" for convenience)

This is my data: Data

In my controller's OnInit function I subscribe to an observable that updates this Data object from time to time. My Controller's onInit function looks like this:

ngOnInit() {
    this.dataEvent.subscribe(Data=> this.Data = Data);
}

When the update happens, the component realises there has been a change, and displays the new data. But does not clear the old data, so I end up with:

This is my data: DataThis is my data: NewData

I am trying to clear that DOM element before rendering the new data such that my component should just display

This is my data: NewData

After the observable triggers the update. I have similar issues with *ngFor as well but I assume there would be a common solution to both.


Solution

  • Okay so I was stupid and didn't heed a console warning I should have. I was running typescript 2.6.0 but the angular project I was working on required an older version. The warning was:

    @angular/compiler-cli@4.3.6 requires typescript@'>=2.1.0 <2.4.0' but 2.6.0 was found instead. 
    
    Using this version can result in undefined behaviour and difficult to debug problems. 
    
    Please run the following command to install a compatible version of TypeScript. 
    
        npm install typescript@'>=2.1.0 <2.4.0' 
    
    To disable this warning run "ng set --global warnings.typescriptMismatch=false".
    

    And simply running:

    npm install typescript@2.3.4
    

    Solved my issue immediately. Hope this helps someone else not waste hours of their life trying to debug a problem when the warning literally says that it can cause difficult to debug problems >.<