简体   繁体   中英

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

I am trying to implement select in Angular 5 but I am constantly getting this

在此处输入图片说明

I've tried many StackOverflow questions already, The only difference is - My components are inside another module within the application which is at the end injected into the main module eventually. I've also tried injecting the FormsModule inside the inner module. I have tried importing ReactiveFormsModule but didn't work.

I've added FormsModule to imports like this

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';

@NgModule({
  declarations: [
    ...CombineComponents
  ],
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule,
    HttpClientModule
  ]
});

and here is my component markup

<label for="ctn" class="d-inline-block pl-1 semi-bold">Current active number</label>
  <select
    #selectElem
    class="custom-select"
    id="ctn"
    (change)="onCTNChange(selectElem.value)"
    formControlName="state"
  >
    <option value="" disabled>Choose a state</option>
    <option *ngFor="let ctn of availableCTN" [ngValue]="ctn.value">
      {{ctn.text}}
    </option>
  </select>

value

[value]="ctn.value"

I was doing a very silly mistake and got into this issue.

  1. Instead of using [ngValue]="ctn.value"
  2. I was supposed to use [value] I was importing formsModule inside parent module, I should have imported it in child module to make [(ngModel)] work
  3. [value] should be [(value)] if we want the default selection show up.

so my final component code is.

<label for="ctn" class="d-inline-block pl-1 semi-bold">Current active number</label>
  <select
    #selectCTN
    class="custom-select"
    id="ctn"
    [(ngModel)]="selectedCTN"
    (change)="onCTNChange(selectCTN.value)"
  >
    <option value="" disabled>Choose a state</option>
    <option *ngFor="let ctn of availableCTN" [(value)]="ctn.value">
      {{ctn.text}}
    </option>
  </select>

[value] will work in this case. In my case also, I haven't used formmodule, just using it inside a tag, working fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM