Hello,

I can try, as a method of learning myself about change detection :)

On Tuesday, June 21, 2016 at 7:35:22 PM UTC+2, Christophe HOARAU wrote:
>
> Hi,
>
> Could someone help me understand why my view is not updated in the 
> following plunker  <http://plnkr.co/edit/GT78jZ4zTmIOAGDYAnwz?p=preview>when 
> I'm using ChangeDetectionStrategy.OnPush.
>

You don't need the ChangeDetectionStrategy.OnPush on that subcomponent, 
that is your main issue. If you just comment out Line 7 in subComponent.ts, 
the example works as (presumably) intended.

But why?

Because OnPush strategy tells Angular component to *only check for changes 
if the reference (on @Input) changes*. But it didn't - your Input is always 
parent component's `data$` observer. Observer did not change.

Now, it also explains (at least partially, at least to me) why you never 
see "test 1" string. Both first and second changes (test 1 and test 2) were 
done in the callback to data$ observer constructor. And piled up there. And 
after all of those, observer already had the latest value "test 2". Then 
you do constructrors and OnInit calls. So by the time change comes in to 
your subcomponent, it only has one meaningful change - the first one it 
sees is from null to test 2.



> According to my understanding when an Observable changes the view should 
> be updated.
>

Observable didn't change. Only it's value. You always have a single 
reference to a single event emitter or in this case, observable. And OnPush 
strategy says to not perform deep checks.
If you comment out the OnPush strategy, then "Angular has to be 
conservative" and run change checks on your objects even if the reference 
to them did not change.

I found out most of this in this nice article 
<http://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html>
.
 

>
> Could someone also explain me why this.dataSource is not initialized in 
> my AppComponent constructor ?
>

I believe it's because of this: you subscribe to this.data$ only in OnInit 
method. If you don't subscribe to observables, they don't run, from what 
I've learned so far.
As a test, I've added a *this.data$.subscribe();* just above that 
console.log line - and really, then I got the dataSource to be logged.


 

>
> Thanks a lot.
>
>
Thank you for a chance to learn something new :)
 

-- 
You received this message because you are subscribed to the Google Groups 
"AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.

Reply via email to