我的应用程序中有一个表单,其中包含title
,price
,category (select)
和imagUrl
数据。我对每个字段都应用了ngModel
,除了select
元素之外,它都工作正常。当我console.log()
表单数据时,我得到每个字段的值,但未定义的select元素的值。我将AngularForms
模块导入了app.module.ts
这是我的product-form-component-html
代码
<form #f="ngForm" (ngSubmit)="save(f.value)" >
<div class="form-group">
<label for="title">Title</label>
<input ngModel name="title" id="title" type="text" class="form-control">
</div>
<div class="form-group">
<label for="price">Price</label>
<div class="input-group">
<span class="input-group-addon">$</span>
<input ngModel name="price" id="price" type="number" class="form-control">
</div>
</div>
<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>
<div class="form-group">
<label for="imageUrl">image URL</label>
<input ngModel name="iamgeUrl" id="imageUrl" type="text" class="form-control">
</div>
<button class="btn btn-primary">Save</button>
</form>
这是product-form-component.ts
文件
import { Component, OnInit } from '@angular/core';
import { CategoryService } from '../../category.service';
import { ProductService } from '../../product.service';
@Component({
selector: 'app-product-form',
templateUrl: './product-form.component.html',
styleUrls: ['./product-form.component.css']
})
export class ProductFormComponent implements OnInit {
categories$;
constructor(categoryService: CategoryService, private productService: ProductService ) {
this.categories$ = categoryService.getCategories();
}
ngOnInit() {
}
save(product) {
console.log(product);
this.productService.create(product);
}
}
这是product-service.ts
import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
@Injectable()
export class ProductService {
constructor(private db: AngularFireDatabase) { }
create(product) {
return this.db.list('/products').push(product);
}
}
我在做什么错?请帮助我提供详细的答案
答案 0 :(得分:0)
这是答案[value]="c.$key"
。我分配了[value]="c.key$"
,这就是为什么我出错了。