Where to initialize components selectors in Angular?

alfredoperez

Alfredo Perez

Posted on September 16, 2020

Where to initialize components selectors in Angular?

TL;DR

When using the selector in the component, it is recommended not to initialize them in the declaration and instead initialize them in the constructor.

export class FindBookPageComponent {
  searchQuery$: Observable<string>;
  books$: Observable<Book[]>;
  loading$: Observable<boolean>;
  error$: Observable<string>;

  constructor(private store: Store<fromBooks.State>) {
    this.searchQuery$ = store.pipe(
      select(fromBooks.selectSearchQuery),
      take(1)
    );
    this.books$ = store.pipe(select(fromBooks.selectSearchResults));
    this.loading$ = store.pipe(select(fromBooks.selectSearchLoading));
    this.error$ = store.pipe(select(fromBooks.selectSearchError));
  }

  search(query: string) {
    this.store.dispatch(FindBookPageActions.searchBooks({ query }));
  }
}
Enter fullscreen mode Exit fullscreen mode

Angular Type Safety

Initializing in the constructor helps because when using the strict mode in TypeScript, the compiler will not be able to know that the selectors were initialized on ngOnInit

The strictPropertyInitialization was added by default in the --strict mode in Angular 9.

The following checks where also added:

{
  "//": "tsconfig.json",
  "compilerOptions": {
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noFallthroughCasesInSwitch": true,
    "strictNullChecks": true
  }
}
Enter fullscreen mode Exit fullscreen mode

The strict-mode allows us to write much safe and robust application. Honestly, I think all Angular application should be written in strict-mode, but it is a little hard to understand every error messages caused by the compiler.


References

  • Angular 9 Strict Mode here
  • Angular Type safety here
  • Strict Property Initialization in TypeScript here
💖 💪 🙅 🚩
alfredoperez
Alfredo Perez

Posted on September 16, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related