![](/img/trans.png)
[英]How to detect mat-autocomplete option is selected in Angular?
[英]Angular5 - How to detect empty or deleted field in mat-autocomplete?
这是我的 html,其中包含材料自动完成功能。
<ng-container *ngSwitchCase="'autocomplete'">
<div [ngClass]="(filter.cssClass || 'col-md-4') + ' mt-2 pt-1'">
<div class="filter-key-label">
{{filter.columnTitle}}
</div>
<div class="filter-form-control d-flex flex-wrap justify-content-left">
<mat-form-field class="full-width">
<input type="text" matInput [formControl]="myControl" [matAutocomplete]="auto" ng-model="blah">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of getOptionsTypeAhead(filter.key) | async" [value]="option" (onSelectionChange)="typeaheadChange($event, filter.key)">
{{ option }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</div>
</div>
</ng-container>
目前我只能使用onSelectionChange
检测选择更改,但它不会检测到该字段最初是否为空,或者在选择一个项目然后删除它之后,我没有选择任何内容并将焦点移出输入字段。
我该如何检测?
我尝试了onkeypress
, ng-change
加上ng-model
(不太确定如何使用它)并进行了change
,但没有任何效果。 图书馆是否已经提供了一些规定,或者我们是否检测到更改和输入字段值?
解决了! 它一直在change
。
最好的部分是它不像onkeypress
,只有在出现blur
事件时才会触发。
我像这样改变了我的<input>
:
<input type="text" matInput [formControl]="myControl" [matAutocomplete]="auto" (change)="handleEmptyInput($event, filter.key)">
控制器看起来像这样:
handleEmptyInput(event: any, key: string){
if(event.target.value === '') {
delete this.filtersApplied[key];
}
}
就像我想要捕获空字段或空值的实例一样:)
由于即时反应,我仍然更喜欢(输入)事件。 但就我而言,我需要一个编程解决方案,因为我需要将自动完成对象 (MatAutocomplete) 传递给未耦合的组件(以获得更大的灵活性)。 这样对我来说效果很好:
@Input() matAutocomplete: MatAutocomplete = null; constructor() { } ngOnInit(): void { if (this.matAutocomplete) { this.matAutocomplete.optionSelected.subscribe((evt: MatAutocompleteSelectedEvent) => { const val = evt.option.value; // here you can do whatever you like with this value. // probably trigger the event, that is binded via (change) or (input) with the input-field }); } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.