gpt4 book ai didi

angular - 如何以编程方式触发 optionSelected Angular Material 自动完成?

转载 作者:行者123 更新时间:2023-12-05 06:13:23 34 4
gpt4 key购买 nike

我有一个 Angular 自动完成组件,我试图在不同的事件之后触发 ts 文件中的 (optionSelected) 事件。我正在使用 this.myControl.setValue(options[1].value) 更新选项设置输入,但是,这不会触发自动完成 (optionSelected) 事件。

这是堆栈 Blitz :

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

import { Component ,ViewChild} from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatAutocompleteTrigger, MatAutocompleteSelectedEvent } from '@angular/material'

/**
* @title Simple autocomplete
*/
@Component({
selector: 'autocomplete-simple-example',
templateUrl: 'autocomplete-simple-example.html',
styleUrls: ['autocomplete-simple-example.css'],
})
export class AutocompleteSimpleExample {
@ViewChild(MatAutocompleteTrigger) _auto: MatAutocompleteTrigger;
myControl = new FormControl();
activeOption
options: string[] = ['One', 'Two', 'Three'];
trigger?: any;

setValue() {
let options = this._auto.autocomplete.options.toArray()
this.myControl.setValue(options[1].value)
}

optionSelected($event: MatAutocompleteSelectedEvent): void {
console.log('event -->', $event);
this.trigger = $event.option.viewValue;
}
}
<form class="example-form">
<mat-form-field class="example-full-width">
<input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" activeOption="activeOption">
<mat-option *ngFor="let option of options" [value]="option" (onSelectionChange)="optionSelected($event)">
{{option}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>

<button (click)="setValue()">Set Value</button>

{{ trigger }}

最佳答案

像这样在 mat-autocomplete 上使用 optionSelected 事件:

html

<mat-autocomplete #autoCompleteUser="matAutocomplete" (optionSelected)="onSelectionChanged($event)">

typescript

onSelectionChanged(event: MatAutocompleteSelectedEvent) {
console.log(event.option.value);
[...]
}

从 mat-options 中删除 onSelectionChange 事件

关于angular - 如何以编程方式触发 optionSelected Angular Material 自动完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63344796/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com