Angular 8 在 2 个独立变量之间创建链接

问题描述 投票:0回答:1

我有一个数组,它根据其中的对象创建视图。可以使用

ngModel
更改对象内部的值。发生的情况是,当我获得数组的响应时,我在相同类型的 2 个不同数组(比如说
mailConfig
tempMailConfig
)中设置了相同的响应。 现在,当我更改
mailConfig
中的值时,
tempMailConfig
的状态也会发生变化。

下面是我在两个变量中分配 api 响应的方式(发生在 OnInit 中)-

this._http.getTrainingConfigByKeys(this.mailConfigKeys).subscribe(response => {
  this.mailConfig = response;
  this.tempMailConfig = response;
});

以下是 HTML 代码 -

<div class="form-group row" *ngFor="let config of mailConfig; let i=index">
  <label for="password" class="col-sm-12 col-md-4 col-form-label">{{config.title}} <span
    class="text-danger">*</span></label>
  <div class="col-sm-12" [ngClass]="{ 'col-md-6 col-lg-6': configValue.control.dirty, 'col-md-8 col-lg-8': !configValue.control.dirty }">
    <input type="text" [class.is-invalid]="false" #configValue="ngModel" [id]="config.propertyKey" [(ngModel)]="config.propertyValue" class="form-control" />
    <!-- Changes in config.propertyValue also changes the same object in tempMailConfig -->
  </div>
</div>

我的项目是用 Angular 8 编写的。我在其他项目中编写了相同类型的逻辑,而且只有 Angular 版本更高,并且没有遇到类似的问题。 我参考了这个answer。当处理单个输入字段时这很好,但对于动态数组如何解决这个问题?我不想使用反应式形式,因为这没有任何复杂的操作。

javascript angular typescript angular8 angular-forms
1个回答
0
投票

尝试使用下面的代码将相同的响应保存在单独的变量中。

this._http.getTrainingConfigByKeys(this.mailConfigKeys).subscribe(response => {
  this.mailConfig = response;
  this.tempMailConfig = [...response];
});

或者您也可以使用切片创建响应数据的新副本并在新变量中分配,如下所示

this._http.getTrainingConfigByKeys(this.mailConfigKeys).subscribe(response => {
  this.mailConfig = response;
  this.tempMailConfig = response.slice();
});
© www.soinside.com 2019 - 2024. All rights reserved.