首页 文章

与ngModel绑定的Angular 2双向数据

提问于
浏览
3

首先,我是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:无法读取undefined的属性'name'

但是我可以轻松地将它绑定到像pageTitle这样的东西 . 任何可以指引我正确方向的想法?

3 回答

  • 1

    我问了这个问题已经有一段时间了,它开始得到一些观点,所以我会添加我的答案 .

    首先,我需要将我的接口更改为类 and 添加构造函数 .

    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';
    
      (...)
    }
    

    现在我在没有任何数据的情况下初始化了所需的品牌,我可以将其绑定到模型 . 希望这可以帮助 .

  • 7

    我认为您需要初始化 newBrand 属性,如下所述:

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

    在您的情况下,此属性永远不会初始化,您有错误:

    无法读取未定义的属性“名称”

  • -1

    你必须为类型编写一个类 . 不是接口 .

    newBrand: Brand = new Brand();
    

相关问题