【问题标题】:Bind interface with html in angular 2 with typescript使用打字稿在 Angular 2 中将接口与 html 绑定
【发布时间】:2018-05-31 02:42:01
【问题描述】:

请帮助我 我想绑定一个接口,即

export interface IEmployee {
    code: string;
    name: string;
    gender: string;
}

使用我的 Html 即

<div class="col-lg-6">
    <div class="form-group">
        <label class="control-label">Code</label>
        <input type="text" class="form-control" [(ngModel)]="employees.code"/>
    </div>
    <div class="form-group">
        <label class="control-label">Name</label>
        <input type="text" class="form-control" [(ngModel)]="employees.name" />
    </div>
    <div class="form-group">
        <label class="control-label">Gender</label>
        <input type="text" class="form-control" [(ngModel)]="employees.gender" />
    </div>
    <div class="form-group">
        <input type="button" class="btn btn-primary" name="Add" value="Add" (click)="onClick(employees)"/>
    </div>
</div>

点击按钮我想从 html 获取输入值到我的类

import { Component,Input } from '@angular/core';
import { HttpModule } from '@angular/http';
import { IEmployee } from '../employee/employee';
import { HomeService } from './home.service';


@Component({
    selector:'my-home',
    templateUrl: 'app/home/home.component.html'

})

export class NewComponent
{
    employees: IEmployee;

    constructor(private _homeService: HomeService) {

    }

    onClick(employee: IEmployee) {
        this._homeService.Add(employee);
    }
}

但我收到以下错误 click here!! 的错误

【问题讨论】:

  • 你可以检查区分大小写的尝试代码而不是代码
  • 是的,我试过了,但还是不行@Eldho
  • stackoverflow.com/a/44378038 可能会有所帮助
  • 我认为你应该初始化员工对象;那么只有你可以分配给一个对象。如果我更改为类而不是接口并创建一个新的员工实例,它就可以工作。
  • 可以分享一下代码吗?

标签: typescript angular2-template angular2-services angular2-directives


【解决方案1】:
export class Employee implements IEmployee{
 code :string;
 name : string;

}

组件

export class NewComponent
{
  employee: Employee;

 constructor(private _homeService: HomeService) {
  employee = new Employee();
 }

//This interface will ensure basic information that IEmployee will be passed 
// to service
onClick(employee: IEmployee) {
    this._homeService.Add(employee);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-21
    • 2017-11-15
    • 2019-09-23
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 2016-10-31
    • 1970-01-01
    相关资源
    最近更新 更多