Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'

My template looks something like as follows:

  <mat-select placeholder="Select Book" name="patient" [(ngModel)]="selectedBook">
     <mat-option *ngFor="let eachBook of books" [ngValue]="eachBook">{{eachBook.name}}</mat-option>
  </mat-select>

I've imported both MatSelectModule and MatOptionModule.

How can we resolve this?

like image 558
Manoj Shrestha Avatar asked Feb 14 '18 07:02

Manoj Shrestha


People also ask

Can't bind to ngModel since it isn't a known property of mat select?

To fix Can't bind to 'ngModel' since it isn't a known property of 'input' error in Angular applications we have to import FormModule in app. module. ts file. If you are using FormBuilder class to create reactive form we have to import ReactiveFormsModule as well to avoid below error.

What is ngValue in angular?

The ng-value directive sets the value attribute of a input element, or a select element.

How do you use ngValue?

Use [value] when you are binding to a string value and only a string value. Or you need access to the option value inside the HTML for automation purposes. Use [ngValue] when you are binding to any type and/or you want the entire option bound instead of just a string.


2 Answers

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,
    ...
]
like image 172
Mark Avatar answered Sep 19 '22 07:09

Mark


You should use value

[value]="eachBook"
like image 30
Sajeetharan Avatar answered Sep 18 '22 07:09

Sajeetharan