mat-autocomplete - программно добавить опцию в массив FilterOptions, затем отсортировать массив по алфавиту - PullRequest
0 голосов
/ 25 сентября 2019

У меня есть элемент mat-autocomplete:

<mat-form-field fxFlex class="cb-margin-top">
    <input type="text" fxFlex placeholder="Trade Type" aria-label="Trade Type" matInput [formControl]="tradeTypeAutocomplete" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete" fxFlex [displayWith]="displayFn" (optionSelected)="tradeTypeSelected($event)">
        <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
            {{displayFn(option)}}
        </mat-option>
    </mat-autocomplete>
</mat-form-field>

ts

public ngOnInit(): void {
    this.tradeTypesLogicService.getList().pipe(takeOne()).subscribe(tts => this.tradeTypes = tts.filter(tt => !!tt.parentId));
    this.filteredOptions = this.tradeTypeAutocomplete.valueChanges
        .pipe(
            startWith(''),
            map(value => typeof value === 'string' ? value : value.label),
            map(label => label ? this._filter(label) : this.tradeTypes.slice())
        );
}

private _filter(label: string): ITradeTypeDto[] {
    const filterValue = label.toLowerCase();
    return this.tradeTypes.filter(option => option.label.toLowerCase().indexOf(filterValue) === 0)
        .concat(this.tradeTypes.filter(option => option.parentLabel.toLowerCase().indexOf(filterValue) === 0));
}

public displayFn(tradeType?: ITradeTypeDto): string | undefined {
    return tradeType ?
        tradeType.label ?
            tradeType.parentLabel ? `${tradeType.parentLabel} - ${tradeType.label}` :
                tradeType.label :
            tradeType.parentLabel ? tradeType.parentLabel :
                undefined :
        undefined;
}

public tradeTypeSelected(e: MatAutocompleteSelectedEvent): void {
    console.log(e);
    this.selectedTradeType = e.option.value;
    this.tradeTypeAlreadyAdded = this.buildActivity.tradeTypesList.find(x => x.id === this.selectedTradeType.id) != undefined;
}

Я добавляю / удаляю опции из mat-autocomplete, добавляя / удаляя элементы из tradeTypes массив выглядит так:

public removeTradeType(): void {
    this.tradeTypes = this.tradeTypes.filter(x => x.id !== this.selectedTradeType.id);
}

public addTradeType(tradeTypeId: number): void {
    const removedTradeType = this.buildActivity.tradeTypesList.find(x => x.id === tradeTypeId);
    this.tradeTypes.unshift(removedTradeType);
}

Параметры добавляются / удаляются из параметров mat-autocomplete, как и ожидалось, однако они не сортируются по алфавиту, пока я не наберу.Как отсортировать параметры mat-autocomplete по алфавиту при каждом добавлении параметра без необходимости ввода?

...