【问题标题】:Set value of angular material select autocomplete programmatically以编程方式设置角度材料选择自动完成的值
【发布时间】:2019-07-08 06:10:00
【问题描述】:

我有一个简单的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 材质 @V 7

【问题讨论】:

  • 所以基本上你想将input 的值设置为一个特定的选项?像渲染组件时的默认值一样?

标签: angular angular-material


【解决方案1】:

您可以执行以下操作来完成此操作。

如果您不能提前确定选项,您可以从 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)
  }

堆栈闪电战

https://stackblitz.com/edit/angular-s3gn1w?embed=1&file=app/autocomplete-simple-example.ts

【讨论】:

  • 如果选项列表中不包含此值,如何以编程方式设置该值?
  • 我做了,但是optionSelected 事件没有被触发。如何触发?
  • 这是通过底层formControl设置值,这样不会触发组件事件。因为这是通过formControl 以编程方式设置值,只需调用optionSelected 事件将在下一行调用的函数...无需使用optionSelected 事件。
猜你喜欢
  • 2020-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多