[英]Set value of angular material select autocomplete programmatically
我有一個簡單的角度材料自動完成功能。 現在我想以編程方式設置此自動填充的值/選擇選項。 這是我的代碼:
hardware.component.html
<tr>
<td class="desc pd7">Firmware</td>
<td>
<div class="form-group mb0">
<mat-form-field class="example-full-width">
<input type="text" placeholder="Select firmware" aria-label="Number" matInput [formControl]="myControlFirmware" [matAutocomplete]="auto1" (keydown.enter)="$event.preventDefault()">
<mat-autocomplete #auto1="matAutocomplete" [displayWith]="displayFirmwares">
<mat-option *ngFor="let firmware of filteredFirmwares | async" [value]="firmware" (onSelectionChange)="getIdFromFirmware($event, firmware)">
{{ firmware.name }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</div>
</td>
</tr>
hardware.component.ts
this.miscellaneousTerminalService.getMiscellaneous('firmware').subscribe(data => {
if(data.success) {
this.availableFirmwares = data.data;
this.filteredFirmwares = this.myControlFirmware.valueChanges
.pipe(
startWith(''),
map(valFirmware => this.filterFirmwares(valFirmware))
);
}
});
filterFirmwares(valFirmware: any): any[] {
return this.availableFirmwares.filter(firmware => {
let name = valFirmware.name ? valFirmware.name : valFirmware;
return firmware.name.toLowerCase().indexOf(name.toLowerCase()) > -1;
});
}
displayFirmwares(firmware: any): string {
return firmware ? firmware.name : firmware;
}
getIdFromFirmware(event, firmware) {
if(event.isUserInput) {
this.selectedFirmware = firmware._id;
}
}
我試圖將我的固件模型設置為所選固件的_id
或名稱,但沒有任何作用。 如何以編程方式設置值。 我正在使用Angular Material @V 7
您可以執行以下操作來完成此操作。
如果您不確定提前選項,例如從API檢索它們,您可以從MatAutocompleteTrigger
獲取它們。
import { MatAutocompleteTrigger } from '@angular/material'
@ViewChild(MatAutocompleteTrigger) _auto: MatAutocompleteTrigger;
let options = this._auto.autocomplete.options.toArray()
單擊按鈕時,此stackblitz將值設置為two
。 我從觸發器中檢索選項並使用選項數組來設置formControl
的值...在您的情況下,它將是this.myControlFirmware.setValue(options[1].value)
setValue() {
let options = this._auto.autocomplete.options.toArray()
this.myControl.setValue(options[1].value)
}
Stackblitz
https://stackblitz.com/edit/angular-s3gn1w?embed=1&file=app/autocomplete-simple-example.ts
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.