首先,我是新来的Typescript和Angular 2,这看起来像一个明显的答案,但我似乎无法得到它的工作。我有以下型号Angular 2与ngModel的双向数据绑定
export interface IBrand {
brandID: number;
name: string;
image: string;
}
然后,我有组件类
import { Component, OnInit } from '@angular/core';
import { Router, RouteParams } from '@angular/router-deprecated'
import { bootstrap } from '@angular/platform-browser-dynamic';
import { IBrand } from './brand';
import { BrandService } from './brand.service';
@Component({
selector: 'data-bind',
templateUrl: 'app/dashboardApp/brands/brand-list.component.html',
styleUrls: ['app/dashboardApp/brands/brand-list.component.css']
})
export class BrandListComponent implements OnInit {
brands: IBrand[];
errorMessage: string;
newBrand: IBrand;
pageTitle: string = 'Brands';
constructor(private _brandService: BrandService,
private _router: Router) {
}
ngOnInit(): void {
this._brandService.getBrands()
.subscribe(
brands => this.brands = brands,
error => this.errorMessage = <any>error);
}
}
然后,我有以下的HTML
<div class="form-group">
<label for="brandName">Brand:</label>
<input type="text" class="form-control" placeholder="Name" id="brandName" [(ngModel)]="newBrand.name" />
</div>
我不能让IBrand的特性工作我得到错误
platform-browser.umd.js:962 ORIGINAL EXCEPTION: TypeError: Cannot read property 'name' of undefined
但是我可以很容易地将它绑定到像pageTitle之类的东西。任何想法都可以指向正确的方向?
非常感谢,我不知道为什么,但当我遵循angular docs https://angular.io/guide/forms#create-the-hero-model-class它定义了构造函数中的字段,并且我得到错误'无法读取未定义的属性',但当我遵循你的答案(移动字段以外的构造函数)我没有得到任何错误 –
这是因为他们正在尝试创建一个具有值的类。希望能够创建一个没有值的类的实例,如果你在每个属性名称之后添加?允许它们为null,或者你可以传入一个值,那么angular docs版本就可以工作了,这取决于你的需求。 – Derked