在放弃更改时,复选框仍具有相同的状态

时间:2019-02-05 00:56:05

标签: javascript angular checkbox

我有点头疼。

我有一个模态,其中显示一些带有复选框的信息,这些信息来自数组,然后设置该数组的复选框状态以及该数组的示例:

this.array = [
{scope: "acc", code: "1", alias: "aaa", selected: true, editable: true},
{scope: "acc", code: "2", alias: "bbb", selected: true, editable: true}
]

我想做的事情是像往常一样玩支票,但是当我单击“ discardChanges”按钮,复选框时,返回以前的状态。

 <div *ngFor="let account of allAccountsList; let i = index;" class="">

          <div class="row">

              <input (click)="saveCheck(account.code, account.scope)" [(checked)]="account.selected"
                type="checkbox" name="genres" value="adventure" id="{{i}}">
              <label for="{{i}}" style="font-family: 'SExtralight'; font-size:14px;"></label>
            </div>
</div>

谢谢大家。

1 个答案:

答案 0 :(得分:0)

此代码:

<div *ngFor="let account of array1; let i = index;">

    <input [checked]="account.selected"
                type="checkbox" 
                name="genres" 
                id="{{i}}">
    <label for="{{i}}" 
              style="font-size:14px;">{{ account.alias }}
    </label>
</div>

不更新基础数组的selected属性。

此代码:

<div *ngFor="let account of array2; let i = index;">

    <input [(ngModel)]="account.selected"
                type="checkbox" 
                name="genres" 
                id="{{i}}">
    <label for="{{i}}" 
              style="font-size:14px;">{{ account.alias }}
    </label>
</div>
<div>

是否更新基础数组的selected属性。

如果要确保不更改基础数组数据,请使用第一组代码。

但是,如果您确实需要在用户单击允许放弃更改选项时跟踪更改,请使用第二组代码。然后在组件中,复制数组以保留原始值:

  ngOnInit() {
    // Save a copy of the original values
    this.array2Copy = this.array2.map(e => ({...e}));
    console.log(JSON.stringify(this.array2Copy));
  }

  discardChanges() {
    // Copy the original values over the array
    this.array2 = this.array2Copy.map(e => ({...e}));
    console.log(JSON.stringify(this.array2Copy));
  }

我在这里有一段这段代码的代码:https://stackblitz.com/edit/angular-arraycopy-deborahk