其实本身联动下拉框是个很简单的活,但是业务提了个要求,就是要允许输入下拉框选项里没有的内容,不接受反驳。
1,新建省市通用组件 AutocompleteProviceCityComponent
<input placeholder="" [(ngModel)]="defaultValue" nz-input (focus)="onInput($event)" (input)="onInput($event)" (ngModelChange)="onValueChange()" [nzAutocomplete]="sourceAuto" /> <nz-autocomplete [compareWith]="compareWith" nzBackfill #sourceAuto> <nz-auto-option *ngFor="let option of options" [nzValue]="option.value" [nzLabel]="option.key"> {{ option.key }} </nz-auto-option> </nz-autocomplete> export class AutocompleteProviceCityComponent implements OnInit {@Input('sourceList') sourceList: any[];//省或市的集合 options: any[] = []; @Input('defaultValue') defaultValue :string;//文本值
@Output() changeValueEvent=new EventEmitter<string>(); constructor() { }
ngOnInit(): void {
} onInput(e: Event): void { const value = (e.target as HTMLInputElement).value; this.options = this.sourceList.filter(s => s.key.indexOf(value) > -1); } onValueChange(){ this.changeValueEvent.emit(this.defaultValue); }
compareWith = (o1: any | string, o2: any): boolean => { if (o1) { return o2.indexOf(o1) > -1; } else { return false; } }; }
2,外层操作逻辑
<app-autocomplete-provice-city (changeValueEvent)="getProvince($event)" [defaultValue]="province" [sourceList]="listOfProvice"></app-autocomplete-provice-city>
<app-autocomplete-provice-city (changeValueEvent)="getCity($event)" [defaultValue]="city" [sourceList]="listOfCity"></app-autocomplete-provice-city>
getProvince(province: any) {
this.queryCities(province);
}
getCity(city: any) {
this.confirmBank.city = city;
}
queryCities(province: string) { if (!province) return; this.province = province; this.city = ''; this.service.getCityList(province).subscribe((ret) => { if (ret) { this.listOfCity = ret; this.listOfCity.forEach(element => { element.key = element.key.substring(element.key.lastIndexOf('_') + 1, element.key.length) }); } }); }
标签:province,city,省市,联动,value,element,key,any,antocomplete From: https://www.cnblogs.com/ashlly/p/17640610.html