我有一个带有自动完成功能的输入表单。它根据用户类型过滤选项。问题是,当单击一个选项时,该字段变为空白,而不是填充用户的选择。
这是我的 HTML:
<mat-form-field class="w-100 mt-25" [class.input-disabled]="form.get('JobAddressID')?.disabled">
<input type="text" matInput placeholder="*Select previously used address" formControlName="JobAddressID" [matAutocomplete]="auto">
<mat-autocomplete (optionSelected)="onSelectionChanged($event)" #auto="matAutocomplete" class="w-100" [displayWith]="displayAddressSelection">
<mat-option *ngFor="let elem of savedLocationsFiltered | async" [value]="elem">
{{elem | truncateString: 60}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
这是我的打字稿文件:
// A bunch of import statements here
@Component({
selector: 'job-location-auth',
templateUrl: './job-location-auth.component.html',
styleUrls: ['./job-location-auth.component.scss', '../../shared/css/tool-tip.scss']
})
export class JobLocationAuthComponent implements OnInit, OnDestroy {
form: FormGroup;
jobAddressID: FormControl;
savedLocations: Observable<{name: string; value: string}[]>;
savedLocationsArray: string[] = [];
savedLocationsFiltered: Observable<string[]>;
private subs = new SubSink();
constructor(
private jobAddressesService: JobAddressesService
) { }
ngOnInit(): void {
this.initialize();
}
ngOnDestroy(): void {
this.subs.unsubscribe();
}
initialize(): void {
this.form = this.locationModel.formGroup;
this.setJobAddressControl();
this.formAddress = this.form.get('JobAddress') as FormGroup;
this.getAddressList();
this.handleSavedLocationSub();
this.filterAddresses();
}
setJobAddressControl(): void {
/* tslint:disable */
this.jobAddressID = this.form.get('JobAddressID') as FormControl;
/* tslint:enable */
this.subs.sink = this.jobAddressID.valueChanges.subscribe((value: number) => {
if (value) {
this.analyticsLoggingService.TrackEvent('JobDetails', 'JobAddress', 'Selected');
}
this.setAddress(+value);
});
}
getAddressList(): void {
this.savedLocations = this.jobAddressesService.getAddresses();
}
handleSavedLocationSub(): void {
this.savedLocations.subscribe(
(addresses: {name: string; value: string}[]) => this.populateSavedAddressArray(addresses)
);
}
filterAddresses(): void {
const jobAddress = this.form.get('JobAddressID');
if (jobAddress) {
this.savedLocationsFiltered = jobAddress.valueChanges.pipe(
startWith(''),
map(value => this._filter(value))
);
}
}
displayAddressSelection(subject: any): string | undefined {
return subject ? subject.name : undefined;
}
onSelectionChanged(event: MatAutocompleteSelectedEvent) {
const jobAddress = this.form.get('JobAddressID');
if (!!jobAddress) {
jobAddress.setValue(event.option.viewValue);
// this.setAddress(jobAddress.value);
}
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.savedLocationsArray.filter(location => { if (!!location) { return location.toLowerCase().includes(filterValue); } });
}
}
我不确定出了什么问题。我查看了自动完成的角度材料文档,据我所知,我尽可能地遵循代码示例,所以这里的代码肯定还有其他问题。