mat-autocomplete の実装に成功し、オート コンプリート ドロップダウンから選択すると正常に動作します。いくつかのテキストを入力し、オート コンプリート フィールドにドロップされた以下を選択せずに他のフィールドに移動すると、問題に直面しています。オートコンプリート フィールドに入力された値を保持します。
この問題を解決するために以下のアプローチを使用しました-
MatAutocompleteTrigger - ts ファイルで使用した以下のコード -
@ViewChild('autoCompleteInput', { static: false,read: MatAutocompleteTrigger }) trigger: MatAutocompleteTrigger; . . . this.trigger.panelClosingActions .subscribe(e => { if (!(e && e.source)) { this.accountForm.get('accountId').setValue=""; this.account.accountId = null; } })
まず第一に、角度のあるライフサイクルフックに保持できません。このトリガーは、angular ライフサイクル フック中には初期化されませんが、後で mat-autocomplete から値を受け取る間に初期化されます。そのため、フィールドにテキストを入力するとすぐに値がクリアされます (以下のオートコンプリート リストを保持します。見栄えがよくありません)。
2.filterOptionsでobservalbleを使用しました(オートコンプリートフィールドでObserableを使用しました)-以下のコードを使用しました-
this.filteredOptions = this.accountForm.get('accountId').valueChanges.pipe( debounceTime(250), distinctUntilChanged(), filter(searchString => typeof searchString === 'string'), filter(searchString => searchString.length > 0), switchMap(searchString => { return this.accountService.autoCompleteBrokerSearch(searchString); }) ); this.filteredOptions.takeUntil(this.ngUnsubscribe).subscribe((lookups: accountEntityModel[]) => { if (lookups.length === 0) { this.account.accountId = null; this.accountForm.get('accountId').patchValue(''); } if(lookups.find(value => value.id !== this.account.id)){ this.account.accountId = null; this.accountForm.get('accountId').patchValue(''); } });
テンプレートコード付き -
<mat-form-field appearance="standard" >
<mat-label>{{ 'account.enterAccount' | translate }}</mat-label>
<input
matInput
formControlName="accountId"
class="search-select"
[matAutocomplete] = "accountAutocomplete"
#autoCompleteInput="matAutocompleteTrigger">
<mat-autocomplete #accountAutocomplete = "matAutocomplete" [displayWith]="displayFn.bind(this)" >
<mat-option [value]="accountOption" *ngFor="let accountOption of filteredOptions | async" (onSelectionChange)="onEnteredAccount(accountOption)" >{{
accountOption.description
}}</mat-option>
</mat-autocomplete>
</mat-form-field>
オートコンプリートから何も選択していない場合にのみフィールドをクリアする必要があり、フォームからもフィールド値をクリアする必要があります。