2016-06-11 104 views
3

首先,我是新來的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之類的東西。任何想法都可以指向正確的方向?

回答

5

自從我問這個問題已經有一段時間了,它開始獲得一些意見,所以我會添加我的答案。

首先,我需要將我的界面更改爲類添加構造函數。

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'; 

    (...) 
} 

現在我有了所需的品牌初始化沒有任何數據,我可以將它綁定到模型。希望這可以幫助。

+0

非常感謝,我不知道爲什麼,但當我遵循angular docs https://angular.io/guide/forms#create-the-hero-model-class它定義了構造函數中的字段,並且我得到錯誤'無法讀取未定義的屬性',但當我遵循你的答案(移動字段以外的構造函數)我沒有得到任何錯誤 –

+0

這是因爲他們正在嘗試創建一個具有值的類。希望能夠創建一個沒有值的類的實例,如果你在每個屬性名稱之後添加?允許它們爲null,或者你可以傳入一個值,那麼angular docs版本就可以工作了,這取決於你的需求。 – Derked

1

我認爲你需要初始化你newBrand屬性如下所述:

export class BrandListComponent implements OnInit { 
    brands: IBrand[]; 
    errorMessage: string; 
    newBrand: IBrand = {}; // <----- 
    pageTitle: string = 'Brands'; 

    (...) 
} 

在你的情況,這個屬性是從來沒有初始化,你有錯誤:

Cannot read property 'name' of undefined

+0

謝謝!我得到一個打字錯誤,現在說「類型'{}'不能分配給'IBrand'類型'propertyID'在類型'{}'中缺少。是我可以忽略的東西還是我需要實例化屬性? – Derked

-1

你必須寫一個類的類。不是接口。

newBrand: Brand = new Brand();