gpt4 book ai didi

angular - 获取 Angular 自动完成值

转载 作者:行者123 更新时间:2023-12-05 08:26:50 24 4
gpt4 key购买 nike

所以我遵循了 Angular 文档中关于 Angular Material Autocomplete 的内容,但是为了从自动完成中获取选择的值,我已经苦苦挣扎了两天。基本上我想要的是自动完成显示人类的名字和姓氏,但选项的值必须是整个人类对象。然后我只想在选择 Human 时控制台记录 SelectedHuman。对此的任何解决方案都可能可行。

这是一个演示项目:https://stackblitz.com/edit/angular-hnu6uj

这是 html 文件:

<input [(ngModel)]="SelectedHuman" (change)="OnHumanSelected()" matInput [formControl]="MyControl" [matAutocomplete]="auto" placeholder="Human">

<mat-autocomplete #auto="matAutocomplete" [displayWith]="AutoCompleteDisplay">
<mat-option *ngFor="let human of arrFilteredHumans | async" [value]="human">
{{human.Name}} - {{human.Surname}}
</mat-option>
</mat-autocomplete>

这是ts文件: 导出类 AutocompleteDisplayExample 实现 OnInit {

  SelectedHuman: Human;
MyControl = new FormControl();
arrFilteredHumans: Observable<Human[]>;
arrHumans = [
new Human('1K59DN3', 27, 'John', 'Smith'),
new Human('9VH23JS', 67, 'William', 'Shakespeare'),
new Human('0QNF1HJ', 44, 'Elon', 'Musk')
];

ngOnInit() {
this.arrFilteredHumans = this.MyControl.valueChanges.pipe(
startWith(''),
map((val) => this.filter(val))
);
}

filter(val: any): Human[] {
return this.arrHumans.filter((item: any) => {
//If the user selects an option, the value becomes a Human object,
//therefore we need to reset the val for the filter because an
//object cannot be used in this toLowerCase filter
if (typeof val === 'object') { val = "" };
const TempString = item.Name + ' - ' + item.Surname;
return TempString.toLowerCase().includes(val.toLowerCase());
});
}

AutoCompleteDisplay(item: any): string {
if (item == undefined) { return }
return item.Name + ' - ' + item.Surname;
}

OnHumanSelected() {
console.log(this.MyControl); //This has the correct data
console.log(this.MyControl.value); //Why is this different than the above result?
console.log(this.SelectedHuman); //I want this to log the Selected Human Object
}
}

export class Human {
constructor(
public ID: string,
public Age: number,
public Name: string,
public Surname: string
) { }
}

最佳答案

点击事件和选择事件是两个不同的事件。你想要选择的事件,而不是点击事件,所以使用 MatAutocomplete 中的 optionSelected:

<mat-autocomplete 
#auto="matAutocomplete"
[displayWith]="AutoCompleteDisplay"
(optionSelected)="OnHumanSelected($event.option)">

<!--
...
-->

</mat-autocomplete>

OnHumanSelected(option: MatOption) {
console.log(option.value);
}

关于angular - 获取 Angular 自动完成值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50505050/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com