Angular : Dynamically push data to observable without changing value in input

我与影子孤独终老i 提交于 2019-12-11 18:49:08

问题


I have used mat-autocomplete with Angular material 7.

this.salesPickerAutoComplete$ = this.autoCompleteControl.valueChanges.pipe(
  startWith(''),
  debounceTime(400),
  distinctUntilChanged(),
  switchMap(value => {
    if (value && value.length > 2) {
      return this.getSalesReps(value);
    } else {
      return of(null);
    }
  })
);

getSalesReps(value: string): Observable<any[]> {
  const params = new QueryDto;
  params.$filter = `substringof('${value}',FirstName) or substringof('${value}',LastName)`;
  params.$select = "UserId,FirstName,LastName,Username";
  return from(this.salesRepresentativesService.GetSalesRepresentatives(params))
    .pipe(
      map(response => response.Data),
      catchError(() => { return of(null) })
    );
}

It works perfectly with search by typing in an input.

My issue is I want the list to auto-populate without typing for some specific functionalities like populate list on-load with some items.

Can anyone tell me how I can do that? How can I push/change some items in mat-autocomplete dynamically?

Below is HTML in which I am binding data

<mat-form-field floatLabel="never">
  <input matInput aria-label="salesRepresentative" type="text" [placeholder]="translationObj.startTypingPlaceholder" autocomplete="off"
    [formControl]="autoCompleteControl" [matAutocomplete]="auto">
  <mat-icon matSuffix class="cursor-pointer">search</mat-icon>
  <mat-autocomplete #auto="matAutocomplete" [displayWith]="createSalesRepString">
    <mat-option *ngFor="let item of salesPickerAutoComplete$ | async;" [value]="item">
      {{item.FirstName}} {{item.LastName}} - (Username: {{item.Username}})
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

回答1:


To set default value you need to set a value to your input field.

<input matInput aria-label="salesRepresentative" type="text" [placeholder]="translationObj.startTypingPlaceholder" autocomplete="off"
    [formControl]="autoCompleteControl" [matAutocomplete]="auto" [(ngModel)]="selectedValue">

Example:

https://stackblitz.com/edit/angular-kmffbi



来源:https://stackoverflow.com/questions/55453366/angular-dynamically-push-data-to-observable-without-changing-value-in-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!