问题
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