首先,我是 Typescript 和 Angular 2 的新手,这似乎是一个显而易见的答案,但我似乎无法让它工作。我有以下模型
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
但是我可以轻松地将它绑定(bind)到 pageTitle 之类的东西。有什么想法可以为我指明正确的方向吗?
最佳答案
自从我提出这个问题以来已经有一段时间了,并且开始有一些观点,所以我会添加我的答案。
首先,我需要将我的接口(interface)更改为一个类并添加一个构造函数。
export class Brand {
constructor() {}
brandID: number;
name: string;
image: string;
}
现在我有了一个构造函数,我可以使用 new 运算符来实例化对象。
export class BrandListComponent implements OnInit {
brands: Brand[];
errorMessage: string;
newBrand: Brand = new Brand();
pageTitle: string = 'Brands';
(...)
}
现在我在没有任何数据的情况下初始化了所需的品牌,我可以将其绑定(bind)到模型。希望这会有所帮助。
关于Angular 2 与 ngModel 的双向数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37765306/