Search code examples
angulartypescriptangular-materialangular-material-5

What does startWith('') typescript code do?


I'm learning Angular 5 with Typescript. I'm trying to implement an angular material autocomplete and I've found the following code which is very obscur to me :

this.filteredStates = this.stateCtrl.valueChanges
  .pipe(
    startWith(''),
    map(state => state ? this.filterStates(state) : this.states.slice())
  );

The full code can be found here : https://stackblitz.com/angular/mdokmnyajmd?file=app%2Fautocomplete-overview-example.ts

I tend to think that when a changed occurs on stateCtrl, then it returns the filterStates(state) result if and only if a concrete element has been selected in autocomplete.

What I don't understand is the use of startWith('') ?! Why not simpling call subscribe on valueChanges ?


Solution

  • valueChanges will not emit any values initially (until state actually changes). When you need to calculate something from initial state you use startWith to make observable emit a value even though it wouldn't normally.

    If you want to process initial value without startWith, you can create another stream

    Observable.of(stateCtrl.value).pipe(
      map(state => state ? this.filterStates(state) : this.states.slice())
    );
    

    which will emit only one value. But it's easier to handle both cases at the same time, so startWith is a good way to do it...