用ngModel进行Angular 2双向数据绑定 [英] Angular 2 two way data binding with ngModel

查看:62
本文介绍了用ngModel进行Angular 2双向数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我是Typescript和Angular 2的新手,这似乎是一个显而易见的答案,但我似乎无法使其正常工作.我有以下型号

First off I am new to Typescript and Angular 2 and this seems like an obvious answer but I can't seem to get it to work. I have the following model

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

And then I have the following 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的属性成功运行,并且出现错误

I can't get the properties of IBrand to work successfully and I get the error

platform-b​​rowser.umd.js:962原始异常:TypeError:无法读取未定义的属性名称"

platform-browser.umd.js:962 ORIGINAL EXCEPTION: TypeError: Cannot read property 'name' of undefined

但是,我可以轻松地将其绑定到诸如pageTitle之类的东西.有什么想法可以指引我正确的方向吗?

However I can bind it easily to something like pageTitle. Any ideas that can point me in the right direction?

推荐答案

自从我问了这个问题已经有一段时间了,它开始得到一些见解,所以我将添加我的答案.

It's been a while since I have asked this question, and it's starting to get some views so I will add my answer.

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

First I would need to change my interface to a class and add a constructor.

export class Brand {
  constructor() {}
  brandID: number;
  name: string;
  image: string;
}

现在我有了一个构造函数,可以使用new运算符实例化该对象.

Now that I have a constructor I can use the new operator to instantiate the object.

export class BrandListComponent implements OnInit {
  brands: Brand[];
  errorMessage: string;
  newBrand: Brand = new Brand();
  pageTitle: string = 'Brands';

  (...)
}

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

Now I have the desired brand initialized without any data and I can bind it to the model. Hope this helps.

这篇关于用ngModel进行Angular 2双向数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆