我有一个简单的angular material autocomplete函数。现在,我想以编程方式设置此自动完成功能的值/所选选项。这是我的代码:
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
答案 0 :(得分:3)
您可以执行以下操作来完成此操作。
如果您不确定提前知道这些选项,例如可以从API检索它们,就可以像这样从MatAutocompleteTrigger
获取它们。
import { MatAutocompleteTrigger } from '@angular/material'
@ViewChild(MatAutocompleteTrigger) _auto: MatAutocompleteTrigger;
let options = this._auto.autocomplete.options.toArray()
单击按钮时,此堆叠闪电将值设置为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