-
-
Save anton-gorbikov/9ad54f89a98ef6cc96a77309670d37f1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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