【问题标题】:Bind value in textbox in Angular 2在Angular 2的文本框中绑定值
【发布时间】:2016-12-16 09:37:24
【问题描述】:

我有一个按钮 btnAdd ,一个文本框和一个带有编辑按钮 btnEdit 在 html 文件中的列表。当我点击 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) { }
}

谢谢,

【问题讨论】:

    标签: angular typescript


    【解决方案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;
      } 
     }
    

    【讨论】:

    • 感谢您的回复。编辑正在运行,但在添加按钮上的列表中添加新项目无法正常工作,而之前的工作..
    • 顺便问一下,在文本框上设置名称并单击添加英雄后,您希望发生什么?
    • 谢谢,它现在可以工作了。我是 Angular 2 的新手,并通过这个简单的示例进行学习。再次感谢。
    • 现在是最后一个问题。如何更新该值并在列表中显示编辑按钮上的更新值。
    • 请将此答案标记为正确。您应该检查您是否已经拥有列表中的值,如果是,则更新此值。如果您不明白如何添加新问题并将问题的链接发送给我以帮助您。
    猜你喜欢
    • 2017-06-02
    • 2016-08-08
    • 2016-05-05
    • 2017-07-06
    • 2016-09-17
    • 1970-01-01
    • 2018-09-02
    • 2018-01-20
    • 1970-01-01
    相关资源
    最近更新 更多