在Angular 2中单击按钮时更新列表项的值

Hit*_*esh 1 typescript angular

我有一个按钮btnAddUpdate,一个文本框和一个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')];


// If not in list please add else Update list value.
      addHero(newHero:string) {
         this.title ="Button Clicked";
          if (newHero) {    
          let hero =  new Hero(14,newHero);   
          this.heroes.push(hero);
         }
      } 


       selectedHero = '';
    onEdit(hero: Hero) {   
    this.selectedHero = hero.name;

     }
Run Code Online (Sandbox Code Playgroud)

下面是html代码:

<input type='text' [value]="selectedHero" #heroName/>
<button (click)="addHero(heroName.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>
Run Code Online (Sandbox Code Playgroud)

Baz*_*nga 5

import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {FormsModule} from '@angular/forms';

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

@Component({
  selector: 'my-app',
  template: `
      <input type="text" [(ngModel)]="heroName" />
      <button (click)="addHero()">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 App {
  heroName: string = '';
  heroes: Array<Hero> = [new Hero(1, 'One'), new Hero(2, 'Two')];
  lastName: string;

  addHero() {
    const findHero = this.heroes.find(hero => hero.name === this.lastName);
    if(findHero) {
      findHero.name = this.heroName;
    } else {
      this.heroes.push(new Hero(3, this.heroName));
    }

    this.heroName = '';
  } 


  onEdit(hero) { 
    this.lastName = hero.name;
    this.heroName = hero.name;
  }
}

@NgModule({
  imports: [ BrowserModule, FormsModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)