Angular5 - 如何检测mat-autocomplete中的空或已删除字段?

10

这是我包含自动完成材料的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检测选择更改,但它无法检测字段最初是否为空,或者在选择项目后将其删除,然后不选择任何内容并将焦点移出输入字段。

我该如何检测到这一点?

我尝试了onkeypressng-changeng-model(不太确定如何使用)和change,但都没有起作用。库中是否已经存在某些规定,或者我们需要检测更改和输入字段的值?

2个回答

12

解决了!问题一直都是在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];
  }
}

就像我想捕获空字段或空值的情况一样 :)


我尝试按照这个例子操作,但是当我在mat-autocomplete中输入值时,输入框无法工作。如果我选择一个项目(而不使用自动完成),它可以正常工作。 - Joh
它不是用来检测按键的,只有在您输入或删除某个值并将焦点移出该字段时才起作用。 - Aakash Verma

0

我仍然更喜欢(input)-event,因为它可以立即响应。 但在我的情况下,我需要一个编程解决方案,因为我需要将自动完成对象(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
});
  }
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接