我需要选择预先选择带有值的自动完成功能,但之后仍然可以更改自动完成功能。这可能吗?我已经尝试在输入元素上使用value属性,但这不起作用。
userlist.component.html
<mat-form-field>
<input type="text" placeholder="Name" aria-label="Name" matInput [formControl]="myControl" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn.bind(this)" (optionSelected)="output($event.option.value)">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{option.display_name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
userlist.component.ts
export class AutoUserlistComponent implements OnInit {
myControl = new FormControl();
options;
filteredOptions: Observable<any[]>;
@Output() change = new EventEmitter<any>();
constructor(
private loaderService: LoaderService
) { }
ngOnInit() {
this.options = this.loaderService.getUser();
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith(''),
map(name => name ? this._filter(name) : this.options.slice())
);
}
displayFn(user): string | undefined {
return user ? user.first_name + ' ' + user.last_name : undefined;
}
private _filter(name: string) {
return this.options.filter(user => {
const searchStr = user.display_name.toLowerCase() + user.ad_login.toLowerCase();
return searchStr.indexOf(name.toLowerCase()) !== -1;
});
}
output(user) {
this.change.emit(user);
}
}
我为你准备了样品。
零件:
private _filter(value: any): Pair[] {
if (typeof value == 'string') {
const filterValue = value.toLowerCase();
return this.options.filter(option => option.name.toLowerCase().includes(filterValue));
} else {
return this.options;
}
}
模板:
<form class="example-form">
<mat-form-field class="example-full-width">
<input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
<mat-autocomplete autoActiveFirstOption #auto="matAutocomplete" (optionSelected)="addpair($event)" [displayWith]="returnfn">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{ option.name }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
我希望,代码可以帮到你!