Search code examples
angularangular2-changedetection

How to implement change detection so the given example works


In this example change detection has not been implemented and the Flip button does not work. I would appreciate hints on how to go about implementing it. The model is the class that needs to drive appearance of the application.


Solution

  • I used *ngIf to remove that div element from the DOM.

    <div *ngIf="show"> 
    

    See more details about ngIf here

    The interesting point here is that ngIf will not just hide the DOM node it will destroy it (remove it from the DOM). Once the condition is truthy new instance will be created.

    Once that is done. I added it back that way the directive will be added again to the newly created elements. And it's life cycle hook ngAfterViewInit will be triggered. See the docs

      ngOnInit() {
        console.log(`SomeComponent[${this.randomNumber}]::ngOnInit`);
      }
    
      ngAfterViewInit() {
        console.log(`SomeComponent[${this.randomNumber}]::ngAfterViewInit`);
      }
    
      ngOnDestroy() {
        console.log(`SomeComponent[${this.randomNumber}]::ngOnDestroy`);
        console.log('');
      }
    

    Here is a simple example to see these hooks in action.