Created
May 27, 2020 09:55
-
-
Save yannickglt/ba4467462b9299f837635e61dee26ac6 to your computer and use it in GitHub Desktop.
Lazy getter in Angular components
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
// Avoid useless computations and combine the property and its initialization method | |
// Live demo at stackblitz.com/edit/angular-lazy-getter | |
import { Component, ChangeDetectionStrategy } from '@angular/core'; | |
import { LazyGetter } from 'lazy-get-decorator'; | |
@Component({ | |
selector: 'lazy-getter-usage', | |
template: ` | |
<h1>{{ sayHelloWithLazyGetter }}</h1> | |
<h1>{{ sayHelloWithoutLazyGetter() }}</h1> | |
<input type="number" [(ngModel)]="counter"> | |
`, | |
changeDetection: ChangeDetectionStrategy.OnPush | |
}) | |
export class LazyGetterUsageComponent { | |
message = 'Hello'; | |
name = 'Jack'; | |
counter = 0; // Used to trigger changes detection | |
@LazyGetter() | |
get sayHelloWithLazyGetter(): string { | |
console.log('sayHello called with lazy getter!'); | |
return `${this.message} "${this.name}"` | |
} | |
sayHelloWithoutLazyGetter(): string { | |
console.log('sayHello called without lazy getter!'); | |
return `${this.message} "${this.name}"` | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment