Jett
Jett

Reputation: 880

Using ngValue with Angular Material autocomplete?

I am passing in an object as my value and need to use [ngValue] as opposed to [value].

My HTML looks like this:

<mat-input-container fxFlex="18" fxFlexOffset="1">
    <input
        matInput
        placeholder="Example"
        [matAutocomplete]="autocomplete"
        [ngModel]="user?.UserName"
        (ngModelChange)="filter($event)"
        [disabled]="disabled"/>
     <mat-autocomplete #autocomplete="matAutocomplete" 
                       (optionSelected)="optionSelected($event)" >
         <mat-option *ngFor="let selectedUser of availableUsers" [ngValue]="selectedUser">
             <span>{{ selectedUser?.UserName }}</span>
         </mat-option>
     </mat-autocomplete>
</mat-input-container>

As a demo, I also have a stackblitz with my error provided here: https://stackblitz.com/edit/angular-5wk4rl?file=app%2Fautocomplete-simple-example.html

I am getting the error:

Template parse errors:

Can't bind to 'ngValue' since it isn't a known property of 'mat-option'.

1. If 'mat-option' is an Angular component and it has 'ngValue' input, then verify that 
   it is part of this module.
2. If 'mat-option' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the 
   '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the 
   '@NgModule.schemas' of this component.

As mentioned in other answer on stack, Angular - Can't bind to 'ngValue' since it isn't a known property of 'mat-option'

Users are suggesting that adding it to the modules file will solve the issue but when I tried that (as seen in my material-module.ts in my stackblitz), the error persists.

Any suggestions? I would appreciate any help!

Upvotes: 1

Views: 2071

Answers (1)

katwhocodes
katwhocodes

Reputation: 2268

 <mat-option *ngFor="let option of options" [value]="option">

Check the documentation here: https://material.angular.io/components/autocomplete/overview

To use the object:

<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
  <mat-option 
    *ngFor="let selectedUser of availableUsers" [value]="selectedUser">
      {{selectedUser.name}}
  </mat-option>
</mat-autocomplete>

in xxx.ts file:

displayFn(user?): string | undefined {
  return user ? user.name : undefined;
}

Upvotes: 2

Related Questions