加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

与ngModel绑定的Angular 2双向数据

发布时间:2020-12-17 17:01:39 所属栏目:安全 来源:网络整理
导读:首先,我是Typescript和Angular 2的新手,这似乎是一个明显的答案,但我似乎无法让它工作.我有以下型号 export interface IBrand { brandID: number; name: string; image: string;} 然后我有组件类 import { Component,OnInit } from '@angular/core';import {
首先,我是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: Cannot read property ‘name’ of undefined

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

解决方法

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

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

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

  (...)
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读