在Angular 2中的文本框中绑定值

时间:2016-12-16 09:37:25

标签: angular typescript

我有一个按钮btnAdd,一个文本框和一个html文件中带有编辑按钮btnEdit的列表。当我点击btnAdd时,它会将一个文本框值插入到列表中,当点击btnEdit时,我想在列表框中显示所选的值。

以下是我的组件代码:

import { Component } from '@angular/core';
import {Hero} from './hero';   

@Component({
  selector: 'my-Home',
   templateUrl: 'app/Home/home.component.html',
})
export class HomeComponent  {  

   title = 'Tour of Heroes';
   newH : Hero;
   heroes = [new Hero(1, 'Windstorm'), new Hero(13, 'Bombasto'),new Hero(15, 'Magneta'), new Hero(20, 'Tornado')];

  addHero(newHero:string) {
     this.title ="Button Clicked";
      if (newHero) {    
      let hero =  new Hero(14,newHero);   
      this.heroes.push(hero);
     }
  } 

  onEdit(hero: Hero) {   
    // want to display selected name in textbox. 

  } 

 }

以下是Html代码:

<input type = 'text' #newHero/>
<button (click)=addHero(newHero.value)>Add Hero!</button> 

    <ul>
       <li *ngFor="let hero of heroes" >          
        <span >{{ hero.id }}</span> {{ hero.name }}        
       <button (click)=onEdit(hero)>Edit!</button>
      </li>
    </ul>

以下是我的课程:

export class Hero {
  constructor(
    public id: number,
    public name: string) { }
}

谢谢,

1 个答案:

答案 0 :(得分:1)

您可以将英雄名称绑定到输入文本值:

<input type='text' [value]="selectedHero" #heroName/>
<button (click)="addHero(heroName.value)">Add Hero!</button> 

export class HomeComponent  {  
  selectedHero = '';
  onEdit(hero: Hero) {   
    this.selectedHero = hero.name;
  } 
 }