2016-06-11 108 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();