当我尝试在angular2应用程序中加载html表单组件时,它不会读取表单一部分的属性。
EXCEPTION: Uncaught (in promise): Error: Error in
http://localhost:3000/app/material/material-new.component.html:15:7
caused by: Cannot read property 'product_name' of undefined
我有另一个相同的组件禁止字段,并且在加载时不会遇到此问题。组件匹配,我很生气。
为什么不读取'product_name'的属性。
继承代码。
创建材料<div class="card container form-container">
<div class="row">
<div class="col-md-12">
<form (ngSubmit)="createMaterial(material)" #materialForm="ngForm" >
<div class="form-group">
<label class="label-text" for="product_name">Product
Name</label>
<input type="text"
class="form-control"
id="product_name"
placeholder="Product name"
required
name="product_name"
#product_name='ngModel'
[(ngModel)]="material.product_name">
<div [hidden]="product_name.valid || product_name.pristine">
Input product name
</div>
</div>
import { Component } from '@angular/core';
import { Material } from './material';
import { MaterialService } from './material.service';
import { Observable } from 'rxjs/Rx';
@Component({
moduleId: module.id,
selector: 'material-new',
templateUrl: 'material-new.component.html',
styleUrls: ['material-new.component.css'],
providers: [ MaterialService ]
})
export class MaterialNewComponent {
material : Material;
submitted : boolean = false;
constructor(
private materialService : MaterialService
) {}
createMaterial( material : Material) {
this.submitted = true;
this.materialService.createMaterial(material)
.subscribe(
data => { return true },
error => { console.log("error saving material")
return Observable.throw(error);
}
)
}
}
答案 0 :(得分:4)
您的错误指向[(ngModel)]="material.product_name"
您的素材对象为undefined
,因为您尚未对其进行初始化。所以你需要做的就是初始化你的对象。
所以改变:
material : Material;
到
material : Material = <Material>{};
它将不再是undefined
。
答案 1 :(得分:0)
您应该使用async
管道来解包Observable
,因为它可以自动订阅和取消订阅。
您需要做的事情:
TS代码:
material: Observable<Material>;
// In createMaterial
this.material = this.materialService.createMaterial(material);
模板:
[(ngModel)]="(material | async)?.product_name"
?
将检查material | async
是否未定义。