【问题标题】:Angular2 ngModel in form. Prevent updating the underlying model [duplicate]Angular2 ngModel 的形式。防止更新基础模型[重复]
【发布时间】:2016-11-04 06:33:25
【问题描述】:

我在这样定义的组件中拥有这些属性。

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 方法是什么?

非常感谢

问候

【问题讨论】:

    标签: angularjs angular angular2-ngmodel


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

    【讨论】:

      【解决方案2】:

      我想这就是你要找的东西:

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

      使用“#”,您可以参考正在更改的对象,如果您点击按钮,您将发送您的信息作为参数。

      查看这个问题了解更多详情

      Angular2 - Update model on button click

      【讨论】:

      • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
      • 感谢@Stefan 的提示
      猜你喜欢
      • 2017-04-05
      • 2019-08-15
      • 1970-01-01
      • 1970-01-01
      • 2019-07-09
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多