【问题标题】:Can't bind to 'ngValue' since it isn't a known property of 'option'无法绑定到“ngValue”,因为它不是“选项”的已知属性
【发布时间】:2018-07-04 19:31:49
【问题描述】:

我正在尝试在 Angular 5 中实现 select,但我不断得到这个

我已经尝试了许多 StackOverflow 问题,唯一的区别是 - 我的组件位于应用程序中的另一个模块内,该模块最终最终注入到主模块中。我也尝试在内部模块中注入FormsModule。我尝试过导入ReactiveFormsModule,但没有成功。

我已将 FormsModule 添加到这样的导入中

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
  ]
});

这是我的组件标记

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

【问题讨论】:

    标签: angular angular-forms


    【解决方案1】:

    [value] 在这种情况下会起作用。在我的情况下,我也没有使用过formmodule,只是在标签内使用它,工作正常。

    【讨论】:

      【解决方案2】:

      我犯了一个非常愚蠢的错误并陷入了这个问题。

      1. 而不是使用[ngValue]="ctn.value"
      2. 我应该使用[value] 我在父模块中导入formsModule,我应该在子模块中导入它以使[(ngModel)] 工作
      3. 如果我们想要显示默认选择,[value] 应该是 [(value)]

      所以我的最终组件代码是。

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

      【讨论】:

        【解决方案3】:

        使用value:

        [value]="ctn.value"
        

        【讨论】:

        • 它正在工作,但我仍然无法绑定该值。它没有将其设置为默认值。
        • 因为添加[ngModel]也会抛出类似的错误
        • ngModel 抛出什么错误?您要导入 FormsModule 吗? .... 从“@angular/forms”导入 {FormsModule};
        • 是的,我正在导入它。 Can't bind to 'ngModel' since it isn't a known property of 'select'
        • 好的,成功了。我正在使用 CommonsModule,我还必须在子模块中导入 FormsModule
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-21
        • 2017-06-21
        • 2017-02-03
        • 1970-01-01
        • 2019-10-10
        相关资源
        最近更新 更多