jeudi 12 septembre 2019

Angular checkboxes maintain checks across records

I have a template driven form in Angular that in one component submits values and in another component has a similar form to edit values (basically just an edit page). Everything seems to work well, but it turns out that my check boxes return with the correct values the first time I load the page, but if I go to a second record, it carries over the checks from the previous record (and adds any existing checks from the new record). So if record 1 has option 1 checked and I navigate to record to and it is supposed to have option 3 checked, it will have both option 1 and option 3 checked. Or if record 2 was supposed to have no checks, it will carry over the option 1 checked from record 1.

Here is an example of the template:

<div class="form-check" *ngFor="let check of options">
                    <input class="form-check-input" type="checkbox" name="chgMips" [checked]="check.checked" (change)="getMips404Checks($event)">
                    <label class="form-check-label">
                      
                    </label>
                  </div>

Here is the model:

options = [
    {value: 'G9642', full: '(G9642) desc1', checked: false},
    {value: 'G9643', full: '(G9643) desc2', checked: false},
    {value: 'G9497', full: '(G9497) desc3', checked: false},
    {value: 'G9644', full: '(G9644) desc4', checked: false}
  ]

The existing check box values for the record come in as a delimited list in the variable chgToEdit.array_Mips404 using the '^' symbol as the delimiter. For example, if option 1 and 2 are checked, the component first receives the value "G9642^G9643". With that in mind, this is what I'm using to set the options:

this.mips404Checked = this.chgToEdit.array_Mips404.split('^');
    for (let i = 0; i < this.mips404Checked.length; i++) {
      for (let j = 0; j < this.options.mips404.length; j++) {
        if (this.options.mips404[j].value === this.mips404Checked[i]) {
          this.options.mips404[j].checked = true;
          break; 
        }
      }
    }

The above code is in ngOnInIt.

As mentioned, the above code works the first time I visit the page or if the page is reloaded. The issue just shows up when I go to another record after having visited the first one. From then, all records show the original checks along with their own.

Since I have to navigate away from the "edit" component to a "list" component in order to navigate to a different record, it seems like going back to a new record's "edit" component would refresh things and give me the correct checks for the new record, but that's not happening. Any help is greatly appreciated!




Aucun commentaire:

Enregistrer un commentaire