首先,我是新來的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