Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import { Component, ChangeDetectionStrategy } from '@angular/core';
import { of } from 'rxjs';
import { map, publishReplay, refCount } from 'rxjs/operators';
@Component({
selector: 'app-root',
template: '<app-tree [data]="data"></app-tree>',
// changed strategy
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {
data = of({
// no changes
}).pipe(
map((data) => {
console.warn('Do some lightweight operation');
return data;
}),
// cached result of transformation
publishReplay(),
refCount()
);
}
import { Component, OnInit, Input, ChangeDetectionStrategy } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Component({
selector: 'app-tree',
template: `
<!-- combined two async pipes into one -->
<ng-container *ngIf="data | async as data">
<div>{{data.title}}: {{data.value}}</div>
<ng-container *ngIf="data.items">
<app-tree *ngFor="let item of data.items; index as i" [data]="getSubtree(i)">
</app-tree>
</ng-container>
</ng-container>
`,
// changed strategy
changeDetection: ChangeDetectionStrategy.OnPush
})
export class TreeComponent {
@Input() data: Observable<any>;
getSubtree(i: number) {
return this.data.pipe(
map((data) => data.items[i])
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment