与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的属性成功工作,我得到错误
但是我可以轻松地将它绑定到像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'; (...) } 现在我在没有任何数据的情况下初始化了所需的品牌,我可以将其绑定到模型.希望这可以帮助. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |