gxclarke
gxclarke

Reputation: 1973

Angular2: how to initially trigger Control.valueChanges

constructor(private _service: LocatorService) {
    this.counties = this.countyTerm.valueChanges
        .debounceTime(300)
        .distinctUntilChanged()
        .switchMap((term: string) => _service.getCounties(term));
}
counties: Observable<County[]>;
countyTerm = new Control();

As expected, this.counties is only populated once a value is entered into the countyTerm bound control.

How can I trigger valueChanges when this component is instantiated so that the set of counties is loaded initially?

I tried the following, but it had no effect (implements OnInit was added to the class):

ngOnInit() {
    this.countyTerm.updateValue('', { emitEvent: true });
}

Upvotes: 3

Views: 2347

Answers (3)

Eladigo
Eladigo

Reputation: 7

With RxJS 6 / 7 new syntax:

this.counties$ = this.countyTerm.valueChanges.pipe(
      startWith(''),
      debounceTime(300),
      distinctUntilChanged(),
      switchMap((term: string) => _service.getCounties(term))
);

Upvotes: 0

Michał Kazimierczak
Michał Kazimierczak

Reputation: 31

Use startWith RxJS operator to emit something before stream.

this.counties = this.countyTerm.valueChanges
    .startwith('')
    .debounceTime(300)
    .distinctUntilChanged()
    .switchMap((term: string) => _service.getCounties(term));

http://reactivex.io/documentation/operators/startwith.html

Upvotes: 3

Matt Burnell
Matt Burnell

Reputation: 2796

Just start your stream out with a fixed value. Something like this:

this.counties = Rx.Observable.of('')
        .concat(this.countyTerm.valueChanges.debounceTime(300))
        .distinctUntilChanged()
        .switchMap((term: string) => _service.getCounties(term));

Upvotes: 4

Related Questions