[英]Angular5 - How to detect empty or deleted field in mat-autocomplete?
This is my html which contains the material 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>
Currently I am able to detect only selection changes using onSelectionChange
but it so not detects if the field is empty initially or when after having selected an item and then deleting it, I do not select anything and shift focus out of the input field.目前我只能使用
onSelectionChange
检测选择更改,但它不会检测到该字段最初是否为空,或者在选择一个项目然后删除它之后,我没有选择任何内容并将焦点移出输入字段。
How do I detect that?我该如何检测?
I tried onkeypress
, ng-change
coupled with ng-model
(was not very sure how to use that) and change
but nothing worked.我尝试了
onkeypress
, ng-change
加上ng-model
(不太确定如何使用它)并进行了change
,但没有任何效果。 Is there some provision already present by the library or do we detect the change and input field value?图书馆是否已经提供了一些规定,或者我们是否检测到更改和输入字段值?
Solved it! 解决了! It was
change
all the time. 它一直在
change
。
The best part is that it doesn't behave like onkeypress
and only fires when there is an blur
event. 最好的部分是它不像
onkeypress
,只有在出现blur
事件时才会触发。
I changed my <input>
like this: 我像这样改变了我的
<input>
:
<input type="text" matInput [formControl]="myControl" [matAutocomplete]="auto" (change)="handleEmptyInput($event, filter.key)">
The controller looks something like this: 控制器看起来像这样:
handleEmptyInput(event: any, key: string){
if(event.target.value === '') {
delete this.filtersApplied[key];
}
}
Just like how I wanted to capture instances of empty fields or blank values :) 就像我想要捕获空字段或空值的实例一样:)
I still prefer (input)-event, because of the instant reaction.由于即时反应,我仍然更喜欢(输入)事件。 But in my case I needed a programmatic solution, because I needed to pass the autocomplete-object (MatAutocomplete) to an uncoupled component (for more flexibility).
但就我而言,我需要一个编程解决方案,因为我需要将自动完成对象 (MatAutocomplete) 传递给未耦合的组件(以获得更大的灵活性)。 This worked for me pretty good that way:
这样对我来说效果很好:
@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.