2016-11-04 31 views
0

我在这样定义的组件中具有这些属性。Angular2 ngModel in form。防止更新基础模型

userDataDefinitions:Array<userDataDefinition>; 
currentDefinition:userDataDefinition = null; 

我然后有一个形式,其在根据向currentDefinition,其被设定为这样的显示数据:

<div *ngFor="let userDataDefinition of userDataDefinitions"> 
      <a href="#" (click)="setCurrentDefinition(userDataDefinition)"> 
       {{ userDataDefinition.key }} 
      </a> 
     </div> 

的形式输入字段使用ngModel这样:

[(ngModel)]="currentDefinition.property" 

这意味着,只要编辑其中一个输入字段,就会立即更新基础currentDefinition和userDataDefinitions,如预期的那样。 我的问题是我应该怎么做,如果我希望底层模型仅在一个动作(如表单提交)时更新? 我应该克隆currentDefinition吗?我应该不使用ngModel吗?

什么是实现这个结果的正确的angular2方法?

非常感谢您

问候

回答

-1

我认为这是你在找什么:

{{heroName}}<br> 
<input [(ngModel)]="heroName" #change> <br> <br> 
<button (click)="update(change.value)">Update Model</button> 

以“#”,你必须在OBJEKT参考这种情况正在改变,如果你再点击你发送信息的按钮作为参数。

看看这个问题的更多细节

Angular2 - Update model on button click

+0

虽然此链接可能回答此问题,但最好在此处包含答案的重要部分并提供供参考的链接。如果链接页面更改,则仅链接答案可能会失效。 - [来自评论](/ review/low-quality-posts/14187529) –

+1

感谢提示@Stefan – KaFu

1

你可以做一个单向的从属性到视图结合,只更新您所选择的事件的性质。以下是一个示例:http://plnkr.co/edit/lNcp7vcEGkozTzB8w4OT?p=info

//our root app component 
import {Component, NgModule} from '@angular/core' 
import {BrowserModule} from '@angular/platform-browser' 
import {FormsModule} from '@angular/forms' 

    @Component({ 
     selector: 'my-app', 
     template: ` 
     <div> 
      <label>{{name}}</label> 
      <input type="text" [ngModel]="name" /> 
      <button (click)="name = 'change'">Change</button> 
     </div> 
     `, 
    }) 
    export class App { 
     name:string; 
     constructor() { 
     this.name = 'Angular2' 
     } 
    } 

    @NgModule({ 
     imports: [ BrowserModule, FormsModule ], 
     declarations: [ App ], 
     bootstrap: [ App ] 
    }) 
    export class AppModule {}