My app component is having a subscribe on a store select. I set ChangeDetectionStrategy
to OnPush
.
I have been reading about how this works; object reference needs to be updated to trigger a change.
When you use async pipe however, Angular expects new observable changes and do MarkForCheck for you.
So, why does my code not render the the channels (unless I call MarkForCheck
) when the subscribe is triggered and I set the channels$
a new observable array of channels.
@Component({
selector: 'podcast-search',
changeDetection: ChangeDetectionStrategy.OnPush, // turn this off if you want everything handled by NGRX. No watches. NgModel wont work
template: `
<h1>Podcasts Search</h1>
<div>
<input name="searchValue" type="text" [(ngModel)]="searchValue" ><button type="submit" (click)="doSearch()">Search</button>
</div>
<hr>
<div *ngIf="showChannels">
<h2>Found the following channels</h2>
<div *ngFor="let channel of channels$ | async" (click)="loadChannel( channel )">{{channel.trackName}}</div>
</div>
`,
})
export class PodcastSearchComponent implements OnInit {
channels$: Observable<Channel[]>;
searchValue: string;
showChannels = false;
test: Channel;
constructor(
@Inject( Store) private store: Store<fromStore.PodcastsState>,
@Inject( ChangeDetectorRef ) private ref: ChangeDetectorRef,
) {}
ngOnInit() {
this.store.select( fromStore.getAllChannels ).subscribe( channels =>{
if ( channels.length ) {
console.log('channels', !!channels.length, channels);
this.channels$ = of ( channels );
this.showChannels = !!channels.length;
this.ref.markForCheck();
}
} );
}
I tried multiple solutions, including using a subject
and calling next
, but that doesn't work unless I call MarkForCheck.
Can anyone tell me how I can avoid calling markForCheck
?