获取 Angular 自动完成值

Fra*_*ank 2 autocomplete angular-material angular

所以我遵循了它的 Angular Material Autocomplete 的 Angular 文档,但我已经花了两天时间从自动完成中获取选择的价值。基本上我想要的是自动完成显示人类的名字和姓氏,但选项的值必须是整个人类对象。然后,我只想在选择 Human 时对 SelectedHuman 进行 console.log。对此的任何解决方案可能都可以。

这是一个演示项目: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>
Run Code Online (Sandbox Code Playgroud)

这是 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
  ) { }
}
Run Code Online (Sandbox Code Playgroud)

G. *_*ter 5

点击事件和选择事件是两个不同的事件。您需要选定的事件,而不是单击事件,因此请使用optionSelectedfrom MatAutocomplete

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

    <!-- 
    ... 
    -->

</mat-autocomplete>

OnHumanSelected(option: MatOption) {
    console.log(option.value);
}
Run Code Online (Sandbox Code Playgroud)