title: Angular - Child component gets destroyed after data change, why?
body: <p>I don't understand on which purpose child components are getting destroyed in Angular when data is changed.</p>
  
  <p>Here's the case: </p>
  
  <p>I have a parent and a child component: </p>
  
  <p><strong>parent.component.html</strong></p>
  
  <pre><code>&lt;div class="parent-content" (click)="toggleChild()"&gt;
     // ...
  &lt;/div&gt;
  &lt;child&gt;&lt;/child&gt;
  </code></pre>
  
  <p>By clicking on the content the child will be toggled (child component will be shown by animation)</p>
  
  <p><strong>parent.component.ts</strong></p>
  
  <p>Here I'm subscribing to the sharedService data changes in my parent...</p>
  
  <pre><code>ngOnInit () {
      let subscription = this.sharedService.myData.subscribe( (data) =&gt; {
          this.data = data;
      });
  }
  </code></pre>
  
  <p>.. as well as in my child (actually the child is wrapper for a dynamically created component, so to be accurate - I'm using the sharedService in my grand-child)</p>
  
  <p><strong>child.component.ts</strong></p>
  
  <pre><code>this.resolver.resolveComponent(component).then(factory =&gt; {
       let componentRef = this.childContainer.createComponent(factory);
  });
  </code></pre>
  
  <p><strong>grand-child.component.ts</strong></p>
  
  <pre><code>ngOnInit () {
      let subscription = this.sharedService.myData.subscribe( (data) =&gt; {
          this.data = data;
      });
  }
  </code></pre>
  
  <p>Now when <strong>myData</strong> changes (due to server response) the child gets destroyed!
  I'm losing all the data of the grand-child because it gets destroyed too!</p>
  
  <p>I read about the component interaction <a href="https://angular.io/docs/ts/latest/cookbook/component-communication.html" rel="nofollow noreferrer">here</a> and still can't figure out when exactly ngOnDestroy will be called, since I don't have any @Inputs...</p>
  
  <p>Maybe I could store the grand-child manipulated data somewhere else before it gets destroyed, but the point is that I need this view to stay open <em>and</em> getting myData updated for parent and grand-child. Thanks for your help!</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>I've noticed that it actually doesn't matter that the child (grand-child) <em>shares</em> the data but the <strong>sheer change of the parent data</strong> causes the destruction (or re-initialization, because the child constructor is called again after destroy) of the child component. How is this problem solved?</p>