Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@anton-gorbikov
Last active April 2, 2019 19:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anton-gorbikov/9ad54f89a98ef6cc96a77309670d37f1 to your computer and use it in GitHub Desktop.
Save anton-gorbikov/9ad54f89a98ef6cc96a77309670d37f1 to your computer and use it in GitHub Desktop.
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