【问题标题】:how update model value when input value is changed in Angularjs2在Angularjs2中更改输入值时如何更新模型值
【发布时间】:2017-01-30 23:19:51
【问题描述】:

我想从输入标签更改模型值,但我不知道如何以最佳方式进行。

这是我为此编写的代码。

<div *ngFor='let l of list'>
    <input #temp [value]='l.test' (blur)='l.test=temp.value'/>
    <span (click)='check(l,temp.value)'></span>
<div>

角码

check(l,temp:string)
{
   console.log(l.test);
   console.log(temp);
}

我想在没有模糊事件的情况下执行此操作。 请建议我任何更好的方法来做到这一点。

【问题讨论】:

    标签: angularjs angular


    【解决方案1】:

    在字段上使用 can [(ngModel)],这将为您提供两种方式绑定字段,只要您输入内容,它就会更改数组中特定元素的 l.test 值。

    标记

    <div *ngFor='let l of list'>
        <input [(ngModel)]='l.test'/>
    <div>
    

    由于Angular 2 rc-5,要使ngModel 双向绑定工作,您必须在@NgModule 中导入FormsModule

    import { FormsModule } from '@angular/forms';
    ///..other imports
    
    @NgModule({
      imports:      [ BrowserModule, FormsModule ], //< added FormsModule here
      declarations: [ AppComponent ],
      bootstrap:    [ AppComponent ]
    })
    

    您可以参考this answer 了解如何在 Angular 2 中使用双向绑定。

    Plunkr here

    【讨论】:

    • 错误:-无法绑定到“ngModel”,因为它不是“输入”的已知属性。
    • @PravinTukadiya 你必须在你的NgModule 中导入FormsModule 才能使用ngModel 指令的双向绑定功能。结帐更新的答案和链接的答案都会对您有所帮助..
    • @PravinTukadiya 对你有帮助吗?
    • 谢谢,@Pankaj Parkar
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多