角材料自动完成力选择 [英] Angular Material Autocomplete force selection
问题描述
在我的angular 5应用程序中,我有一些matAutocomplete,但是我想强制选择没有建议的内容,因此我遵循这种方法: stackblitz 但由于某种原因,我遇到了一个问题:
In my angular 5 application I have some matAutocomplete, but I want to force the selection of oone of suggestions, so I am following this approach: stackblitz but for some reason in one case I have an issue:
无法读取未定义的属性"panelClosingActions" 在CustomerDetailComponent.countryClosingActions(customer-detail.component.ts:199) 在CustomerDetailComponent.ngAfterViewInit
Cannot read property 'panelClosingActions' of undefined at CustomerDetailComponent.countryClosingActions (customer-detail.component.ts:199) at CustomerDetailComponent.ngAfterViewInit
我有多个matAutocomplete,但是只有一个有问题. (有关此方法的信息,请参见 github
I have multiple matAutocomplete but only this one have problems. (info about this method is here github
html
<mat-form-field>
<input matInput #nation placeholder="{{'customer.detail.labels.country'
| translate }}" required [matAutocomplete]="tdAuto" name="country"
#count="ngModel" [(ngModel)]="selected.country"
(ngModelChange)="searchCountry($event)">
<mat-autocomplete #tdAuto="matAutocomplete" [displayWith]="displayFn">
<mat-option (onSelectionChange)="setCountry(country)" *ngFor="let country of countries" [value]="country">
<div class="row">
<img src="assets/img/flags24/{{country.alpha2Code | lowercase}}.png" />
<span>{{country.name}} ({{country.alpha2Code}})</span>
</div>
</mat-option>
</mat-autocomplete>
</mat-form-field>
组件
@ViewChild('nation', { read: MatAutocompleteTrigger }) trigger: MatAutocompleteTrigger;
subscription: Subscription;
ngAfterViewInit() {
this.countryClosingActions();
}
private countryClosingActions(): void {
if (this.subscription && !this.subscription.closed) {
this.subscription.unsubscribe();
}
this.subscription = this.trigger.panelClosingActions
.subscribe(e => {
console.log('closing')
if (!e || !e.source) {
this.selected.country = null;
this.selfCountry = null;
}
},
err => this.countryClosingActions(),
() => this.countryClosingActions());
}
推荐答案
使用模糊事件和matAutocomplete输出事件(optionSelected),可以强制用户选择选项.
Using blur event and matAutocomplete output event (optionSelected) we can force user to select option.
<mat-form-field class="example-full-width">
<input type="text" placeholder="Country*" matInput formControlName="country" [matAutocomplete]="countryAutoList" (blur)="checkCountry()">
<mat-autocomplete autoActiveFirstOption #countryAutoList="matAutocomplete" (optionSelected)="countryClick($event)">
<mat-option *ngFor="let item of countryList" [value]="item.Name">{{item.Name}}</mat-option>
</mat-autocomplete>
</mat-form-field>
ts文件功能
countryClick(event: any) {
this.selectedCountry = event.option.value;
}
checkCountry() {
if (!this.selectedCountry || this.selectedCountry !== this.signatureFormGroup.controls['country'].value) {
this.signatureFormGroup.controls['country'].setValue(null);
this.selectedCountry = '';
}
}
这篇关于角材料自动完成力选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!