Angular2:将下拉选择绑定到我的intefrace中

时间:2017-01-25 13:25:50

标签: angular typescript drop-down-menu model-binding

我正在编写一个包含两个文本表单和一个按钮的表单:

<form noValidate (ngSubmit)="onSubmit(login)" [formGroup]="login">
Username:<br> <input type="text" formControlName="username"><br>
<div class="error"
    *ngIf="login.get('username').hasError('required') && login.get('username').touched">
    Username required</div>

Password:<br> <input type="password" formControlName="password"><br>
<div class="error"
    *ngIf="login.get('password').hasError('required') && login.get('password').touched">
    Password required</div>

<br> <input type="submit" value="Login" [disabled]="login.invalid">

这是我的组件

export class LoginComponent implements OnInit {
    login: FormGroup;
    response: ResponseInterface;

    constructor() {
    }

    ngOnInit() {
        this.login = new FormGroup({
      username: new FormControl('', [Validators.required, Validators.required]),
        password: new FormControl('', [Validators.required, Validators.required])});
    }

    onSubmit({ value, valid }: { value: LoginInterface, valid: boolean }) {
       console.log(value, valid);
    }
}

和我的LoginInterface:

export interface LoginInterface {
  username: String;
  password: String;
}

现在我已经编写了一个显示下拉列表的组件(在互联网上找到),所以我想将选定的值绑定到我的登录界面。这是组件

export class DropdownosComponent {
   private list = [
      { id: 1, name: 'ONE' },
      { id: 2, name: 'TWO' },
      { id: 3, name: 'THREE'}
   ];
   private current: number = 1;

   private setCurrent(id: number): void {
      this.current = id;
   }
   public getCurrent(): string {
      return this.list.find((item: any) => item.id == this.current).name;
   }
}

及其模板

<select #select [(ngModel)]="current"
(change)="setCurrent(select.value)">
   <option *ngFor="let item of list" [value]="item.id">{{item.name}}</option>
</select>

和LoginInterface成为:

export interface LoginInterface {
  username: String;
  password: String;
  dropdown: String;
}

现在,如果我将它放入我的LoginComponent模板中,如何正确地将选择绑定到LoginInterface下拉列表中?

0 个答案:

没有答案