Angular 5 ngModel更改UI中的值而不保存它

时间:2019-07-09 13:29:48

标签: html angular typescript

在我的表单中,我有一个带有绑定变量的选择。如果我尝试更改并保存值,则可以正常工作,但是如果我尝试更改模式中的值,而不是保存它,则在我的UI中关闭模式(因此我不保存该值),我会看到更改后的值显然在我的数据库中,该值未更改。

component.html

 <select class="form-control m-input" id="type" formControlName="type"
  [ngClass]="{ 'is-invalid': submitted && formcontrols.type.errors }" name="type"
  (change)="changeType($event, newParameter.type)"
   [(ngModel)]="newParameter.type">
     <option [ngValue]="'STRUCT'">STRUCT</option>
     <option [ngValue]="'NUM'">NUM</option>
     <option [ngValue]="'BOOLEAN'">BOOLEAN</option>
     <option [ngValue]="'DATE'">DATE</option>
 </select>

component.ts

changeType(event, type){
    type= this.createParameterForm.get('type').value;
    if(type==="NUM"){
        this.initNUMControlsForm();
    }
    else if(type ==="STRUCT"){
        this.initStructControlsForm();
    }
    else{
        this.initControlsForm();
    }
}

如何避免这个问题?

1 个答案:

答案 0 :(得分:0)

通常,您需要在开始时创建对象的另一个实例,然后通过表单修改该对象。您可以通过const newObj = {...originalObj}const newObj = JSON.parse(JSON.stringify(originalObj))

创建新对象

如果用户尝试保存,请将新对象传递给保存功能,并在成功保存后将其复制回原始对象

如果用户取消,请不要执行任何操作,因为您的原始对象未更改