Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Angular Autocomplete Value

So I followed the Angular documentation of it's Angular Material Autocomplete but have been battling two days with getting the value of the selection from the Autocomplete. Basically what I want is for the Autocomplete to display the Humans' names and surnames, but the option's value must be the entire Human object. I then just want to console.log the SelectedHuman whenever a Human is selected. Any solution to this would probably do.

Here is a demo project to play with: https://stackblitz.com/edit/angular-hnu6uj

Here is the html file:

<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>

Here is the ts file: export class AutocompleteDisplayExample implements 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
  ) { }
}
like image 692
Frank Avatar asked Mar 10 '26 17:03

Frank


2 Answers

The click event and the selection event are two different events. You want the selected event, not the click event, so use optionSelected from MatAutocomplete:

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

    <!-- 
    ... 
    -->

</mat-autocomplete>

OnHumanSelected(option: MatOption) {
    console.log(option.value);
}
like image 55
G. Tranter Avatar answered Mar 13 '26 08:03

G. Tranter


Here is a Stackblitz link.

Here is code

   OnHumanSelected(SelectedHuman) {
    console.log(SelectedHuman); // get from view
    console.log(this.SelectedHuman); // get from variable
  }

HTML File

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

<mat-autocomplete #auto="matAutocomplete" [displayWith]="AutoCompleteDisplay">
    <mat-option (click)="OnHumanSelected(SelectedHuman)"  *ngFor="let human of arrFilteredHumans | async" [value]="human">
    {{human.Name}} - {{human.Surname}}
  </mat-option>
</mat-autocomplete>
like image 29
Sharma Vikram Avatar answered Mar 13 '26 08:03

Sharma Vikram



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!