首页 > 解决方案 > Angular - 未在 ngForm 对象中捕获所选选项

问题描述

编辑删除不相关的代码。

我正在尝试将表单对象打印到控制台,但未显示所选选项。它在控制台中显示为未定义。

在此处输入图像描述

我已经把代码放在下面了。如果有人可以指导此特定代码有什么问题,那将很有帮助。让我知道是否需要任何其他信息。

组件.html:

<form #f="ngForm" (ngSubmit)="save(f.value)">

....

  <div class="form-group">
    <label for="category">Category</label>
    <select ngModel name="category" id="category" class="form-control">
      <option value=""></option>
      <option *ngFor="let c of categories$ | async" [value]="c.key">
        {{ c.name }}
      </option>
    </select>
  </div>

....

组件.ts:

import { CategoryService } from './../../category.service';

....

export class ProductFormComponent implements OnInit {

  categories$;

  constructor(categoryService: CategoryService) {
    this.categories$ = categoryService.getCategories();
  }

  save(product) {
    console.log(product);
  }

....

类别.Service.ts:

import { AngularFireDatabase } from 'angularfire2/database';

....

  getCategories() {
    return this.db
      .list('/categories', ref => ref.orderByChild('name'))
      .valueChanges();
  }

....

我想从 Firebase 数据库中突出显示要在对象中捕获的值。如果我把 c.name 我得到用户友好的名称。

Firebase 数据库结构。

标签: angulartypescriptfirebasengmodel

解决方案


//you need to bind object field in selection [(NgModel)] like below example


    <select [(ngModel)]="urobject.category" name="category" id="category" class="form-control">
          <option value=""></option>
          <option *ngFor="let c of categories$ | async" [value]="c.key">
            {{ c.name }}
          </option>


     </select>

推荐阅读