Skip to content

Instantly share code, notes, and snippets.

@yannickglt
Created May 27, 2020 09:55
Show Gist options
  • Save yannickglt/ba4467462b9299f837635e61dee26ac6 to your computer and use it in GitHub Desktop.
Save yannickglt/ba4467462b9299f837635e61dee26ac6 to your computer and use it in GitHub Desktop.
Lazy getter in Angular components
// 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