Angular - 所选选项未在 ngForm 对象中捕获

Angular - Selected option not being captured in ngForm object

已编辑以删除不相关的代码。

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

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

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

....

Component.ts:

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

....

export class ProductFormComponent implements OnInit {

  categories$;

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

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

....

Category.Service.ts:

import { AngularFireDatabase } from 'angularfire2/database';

....

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

....

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

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

我在下面link找到了答案。我们应该使用 .snapshotChanges() 而不是 .valueChanges(),因为前者 returns 是一个没有任何元数据的 Observable。

Upgrading to AngularFire 5.0

具有更改的更新文件如下。

Category.service.ts:valueChanges() 更改为 snapshotChanges()

import { AngularFireDatabase } from 'angularfire2/database';

....

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

....

Component.html:在select选项插值中,将c.name改为c.payload.val().name

<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="blank"></option>
      <option *ngFor="let c of categories$ | async" [value]="c.key">
        {{ c.payload.val().name }}
      </option>
    </select>
  </div>

....