简体   繁体   English

Angular 2 双向数据绑定与 ngModel

[英]Angular 2 two way data binding with ngModel

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.首先,我是 Typescript 和 Angular 2 的新手,这似乎是一个显而易见的答案,但我似乎无法让它发挥作用。 I have the following model我有以下型号

export interface IBrand {
    brandID: number;
    name: string;
    image: string;
}

Then I have the component class然后我有组件类

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);
    }    
}

And then I have the following html然后我有以下 html

<div class="form-group">
    <label for="brandName">Brand:</label>
    <input type="text" class="form-control" placeholder="Name" id="brandName" [(ngModel)]="newBrand.name" />
</div>

I can't get the properties of IBrand to work successfully and I get the error我无法使 Ibrand 的属性成功运行,并且出现错误

platform-browser.umd.js:962 ORIGINAL EXCEPTION: TypeError: Cannot read property 'name' of undefined平台浏览器.umd.js:962 原始例外:类型错误:无法读取未定义的属性“名称”

However I can bind it easily to something like pageTitle.但是我可以很容易地将它绑定到 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;
}

Now that I have a constructor I can use the new operator to instantiate the object.现在我有了一个构造函数,我可以使用 new 运算符来实例化对象。

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.希望这可以帮助。

You could follow this approach if you don't want to use class.如果你不想使用类,你可以遵循这种方法。

export interface IBrand {
brandID: number;
name: string;
image: string;
}

And now you could create empty objects for typed variables like this.现在你可以为这样的类型变量创建空对象。

brand: IBrand = {} as IBrand;

Avoid using classes if you just want to use it for type safety instead use interface as best practice to make your bundle size smaller.如果您只想将类用于类型安全,请避免使用类,而不是使用接口作为最佳实践来缩小包大小。

I think that you need to initialize your newBrand property as described below:我认为您需要按如下所述初始化您的newBrand属性:

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

  (...)
}

In your case, this property is never initialized and you have the error:在您的情况下,此属性从未初始化并且您有错误:

Cannot read property 'name' of undefined无法读取未定义的属性“名称”

You probably found out already, but you can/should use: newBrand: IBrand = {};您可能已经发现了,但是您可以/应该使用: newBrand: IBrand = {}; if your interface properties are optional:如果您的接口属性是可选的:

export interface IBrand {
    brandID?: number;
    name?: string;
    image?: string;
}

You have to write a class for types.您必须为类型编写一个类。 Not Interfaces.不是接口。

newBrand: Brand = new Brand();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM