Angular 2 与 ngModel 的双向数据绑定(bind)

标签 angular

首先,我是 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

但是我可以轻松地将它绑定(bind)到 pageTitle 之类的东西。有什么想法可以为我指明正确的方向吗?

最佳答案

自从我提出这个问题以来已经有一段时间了,并且开始有一些观点,所以我会添加我的答案。

首先,我需要将我的接口(interface)更改为一个类添加一个构造函数。

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

  (...)
}

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

关于Angular 2 与 ngModel 的双向数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37765306/

相关文章:

angular - Jest/Ionic 4 beta - import { Platform } from '@ionic/angular' ;获取 SyntaxError : Unexpected token export in Jest testing, 不是 Ionic

angular - 在 azure map 中创建具有一百万个点的矢量切片

Angular Material mat-select - 显示计数以及多重选择中的第一个选定值

html - Material 表中的 Angular 6 索引不起作用

Angular 7、Ngrx、Rxjs 6 - 在延迟加载的模块之间访问状态

Angular 2 Observable.forkJoin 与 for 循环

angular - 将数组中的值附加到 BehaviorSubject

angular - 如何在 Angular 6 中导入 rxjs 计时器?

angular - 如何在没有组件的情况下从 Angular 9+ 中的延迟加载模块动态注入(inject)服务?

javascript - Angular 5 - 如何重定向到具有特定 header 的外部 URL?