【问题标题】:Using ngModel within an option select在选项选择中使用 ngModel
【发布时间】:2018-12-11 10:47:59
【问题描述】:

我想将 api 调用中的属性传递给提交函数,但不确定它为什么不起作用。我认为这与选项选择或重新格式化输入有关。

遇到错误Error: No value accessor for form control with name: 'employee_id'

form.component.html

<select>
 <option 
   *ngFor="let employee of employees" 
   name="employee_id" 
   [(ngModel)]="employee_id">
   {{ employee.name }}
 </option>
</select>

<button 
  (click)="submitMeetingRequirements()" 
  class="btn btn-success">
  Suggest Meeting
</button>

这是来自form.component.ts的提交函数

submitMeetingRequirements() {
  this._meetingService.submitMeetingRequirements(
    this.employee_id)
    .subscribe(res => this.suggestions = res["suggestions"])
}

【问题讨论】:

    标签: html angular typescript api angular-ngmodel


    【解决方案1】:

    用

    固定
    <select [(ngModel)]="employee_id" name="employee_id">
      <option 
        *ngFor="let employee of employees"
        value="{{employee.id}}">
        {{ employee.name }}
      </option>
    </select>
    

    【讨论】:

      【解决方案2】:

      在select 标签上使用[(ngModel)],而不是option 标签。像这样的:

      <select [(ngModel)]="employee_id">
       <option 
         *ngFor="let employee of employees" 
         name="employee_id" >
         {{ employee.name }}
       </option>
      </select>
      
      <button 
        (click)="submitMeetingRequirements()" 
        class="btn btn-success">
        Suggest Meeting
      </button>
      

      这里有一个Working Sample StackBlitz 供您参考。

      【讨论】:

      • 我试过了,我得到了Error: If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions.
      • "name" 属性也适用于选择,您不能为同一个选择中的每个选项设置相同的名称。您可以尝试使用[name]="employee.name + '_id' ",显然员工姓名必须不同
      • 我试过了,但我得到了错误消息Cannot read property 'name' of undefined
      • name of undefined 表示列表中的“员工”未定义。如果您使用[name]="employee.name + '_id' ",则必须在选项标签中的选择内设置它;否则,如果您使用name="employee_id",则必须在选择标签中使用它
      猜你喜欢
      • 1970-01-01
      • 2017-07-13
      • 2015-09-01
      • 1970-01-01
      • 2020-03-25
      • 2022-01-06
      • 1970-01-01
      • 2021-06-02
      • 2017-01-16
      相关资源
      最近更新 更多