|
1 | 1 | import { ChangeDetectorRef, inject, Injectable } from '@angular/core';
|
2 | 2 | import { TickScheduler } from './tick-scheduler';
|
3 | 3 |
|
| 4 | +/** |
| 5 | + * Provides rendering functionality regardless of whether `zone.js` is present |
| 6 | + * or not. It must be provided at the component/directive level. |
| 7 | + * |
| 8 | + * @usageNotes |
| 9 | + * |
| 10 | + * ### Rerender zone-less app on route changes |
| 11 | + * |
| 12 | + * ```ts |
| 13 | + * @Component({ |
| 14 | + * selector: 'app-root', |
| 15 | + * template: '<router-outlet>', |
| 16 | + * // 👇 `RenderScheduler` is provided at the component level |
| 17 | + * providers: [RenderScheduler], |
| 18 | + * changeDetection: ChangeDetectionStrategy.OnPush, |
| 19 | + * }) |
| 20 | + * export class AppComponent implements OnInit { |
| 21 | + * constructor( |
| 22 | + * private readonly router: Router, |
| 23 | + * private readonly renderScheduler: RenderScheduler |
| 24 | + * ) {} |
| 25 | + * |
| 26 | + * ngOnInit(): void { |
| 27 | + * this.router.events |
| 28 | + * .pipe(filter((e) => e instanceof NavigationEnd)) |
| 29 | + * .subscribe(() => this.renderScheduler.schedule()); |
| 30 | + * } |
| 31 | + * } |
| 32 | + * ``` |
| 33 | + * |
| 34 | + * ### Rerender component on interval |
| 35 | + * |
| 36 | + * ```ts |
| 37 | + * @Component({ |
| 38 | + * selector: 'app-interval', |
| 39 | + * template: '{{ elapsedTime }}ms', |
| 40 | + * // 👇 `RenderScheduler` is provided at the component level |
| 41 | + * providers: [RenderScheduler], |
| 42 | + * changeDetection: ChangeDetectionStrategy.OnPush, |
| 43 | + * }) |
| 44 | + * export class IntervalComponent implements OnInit { |
| 45 | + * elapsedTime = 0; |
| 46 | + * |
| 47 | + * constructor(private readonly renderScheduler: RenderScheduler) {} |
| 48 | + * |
| 49 | + * ngOnInit(): void { |
| 50 | + * setInterval(() => { |
| 51 | + * this.elapsedTime += 1000; |
| 52 | + * this.renderScheduler.schedule(); |
| 53 | + * }, 1000); |
| 54 | + * } |
| 55 | + * } |
| 56 | + * ``` |
| 57 | + */ |
4 | 58 | @Injectable()
|
5 | 59 | export class RenderScheduler {
|
6 | 60 | constructor(
|
7 | 61 | private readonly cdRef: ChangeDetectorRef,
|
8 | 62 | private readonly tickScheduler: TickScheduler
|
9 | 63 | ) {}
|
10 | 64 |
|
| 65 | + /** |
| 66 | + * Marks component and its ancestors as dirty. |
| 67 | + * It also schedules a new change detection cycle in zone-less mode. |
| 68 | + */ |
11 | 69 | schedule(): void {
|
12 | 70 | this.cdRef.markForCheck();
|
13 | 71 | this.tickScheduler.schedule();
|
|
0 commit comments