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

后端 未结 4 1111
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-17 10:23

I\'m using angular 5 and I\'m getting the console error:

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

相关标签:
4条回答
  • 2021-01-17 10:52

    You should use value

    [value]="eachBook"
    
    0 讨论(0)
  • 2021-01-17 10:52

    The accepted answer is not a solution but a work-around, as value and [ngValue] serve different purposes. value can be used for simple string values, whereas [ngValue] is necessary to support non-string values.

    Per the documentation:

    If you have imported the FormsModule or the ReactiveFormsModule, this value accessor will be active on any select control that has a form directive. You do not need to add a special selector to activate it.

    If you are getting this error, you most likely need to import either FormsModule or ReactiveFormsModule into your app.

    For example, in app.module.ts:

    import { FormsModule } from '@angular/forms';
    
    // ...
    
    imports: [
        FormsModule,
        ...
    ]
    
    0 讨论(0)
  • 2021-01-17 11:01

    for mat-autocomplete, to use items instead of strings, for mat-option, ngValue wasn't available, however with [value], we can access the object by using option.value instead of option.viewValue:

    allFruits: Item[] = [
        {
          name: 'hello',
          selected: true,
        },
        {
          name: 'world',
          selected: false,
        }
      ];
    
    
    <mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
        <mat-option *ngFor="let fruit of filteredFruits | async" [value]="fruit">
          {{fruit.name}} {{fruit.selected}}
        </mat-option>
      </mat-autocomplete>
    
    
    selected(event: MatAutocompleteSelectedEvent): void {
        console.log('selected ', event.option.value); <----- THIS
        console.log('selected ', event.option.viewValue); <---- NOT THIS
    }
    

    with option.value you get the object. With option.viewValue you will get a string representation of the innerHTML that the user sees.

    0 讨论(0)
  • 2021-01-17 11:09

    I have met the same issue. The solution for me is to import 'ReactiveFormsModule'. So you can use [ngValue] to bind an object.

    0 讨论(0)
提交回复
热议问题