双向绑定以Angular5显示类型错误:无法读取属性';标题';空的
我正在用Angular5制作一个表单,在后台使用firebase进行学习。我的双向绑定不起作用。这是给我下面的控制台错误双向绑定以Angular5显示类型错误:无法读取属性';标题';空的,angular,firebase,angular5,Angular,Firebase,Angular5,我正在用Angular5制作一个表单,在后台使用firebase进行学习。我的双向绑定不起作用。这是给我下面的控制台错误 TypeError: Cannot read property 'title' of null 这是我的模板: <form #f="ngForm" (ngSubmit)="save(f.value)"> <div class="form-group"> <label for="title"
TypeError: Cannot read property 'title' of null
这是我的模板:
<form #f="ngForm" (ngSubmit)="save(f.value)">
<div class="form-group">
<label for="title">Title</label>
<input #title="ngModel"
[(ngModel)]="product.title" name="title" id="title" type="text" class="form-control" required>
<div class="alert alert-danger mt-1" *ngIf="title.touched && title.invalid">
Title is required.
</div>
</div>
<!-- other input fields here -->
</form>
以下是服务:
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);
}
getAll() {
return this.db.list('/products').snapshotChanges().map(categories => {
return categories.map(c => ({ key: c.payload.key, ...c.payload.val() }));
});
}
get(productId) {
return this.db.object('/products' + productId).valueChanges();
}
}
请告诉我我的代码出了什么问题。我是新手。我无法解决它。请提供帮助。出现异常的原因是dom初始化时未定义产品属性 有两个选择,两个绕过问题:
*ngif
整个表单
像这样使用?
运算符:
这是因为绑定时产品尚未设置。试试这个?运营商[(ngModel)]=“产品?.title”
或ngIf:我认为这是因为url'/products'+productId
应该是'/products/'+productId
对吗?@Orlandster谢谢。这是个错误。
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);
}
getAll() {
return this.db.list('/products').snapshotChanges().map(categories => {
return categories.map(c => ({ key: c.payload.key, ...c.payload.val() }));
});
}
get(productId) {
return this.db.object('/products' + productId).valueChanges();
}
}