简体   繁体   中英

Angular: Update template without ngModel

I'm trying to achieve multi-select functionality and display the selected items using checkoxes. HTML

<div class="multiselect">
    <div class="selectBox" (click)="showCheckboxes()">
         <select>
             <option>{{selectedBaseLicences}}</option>
         </select>
    <div class="overSelect"></div>
 </div>
<div id="checkboxes">
    <ng-container *ngFor="let base of baseLicences">
        <label class="checkbox">
            <input type="checkbox" name="checkbox1" (click)="myFunction(base)">
            <span class="checkbox__input"></span>
            <span class="checkbox__label">{{base}}</span>
         </label>
    </ng-container>
 </div>

TS

public selectedBaseLicences: string[] = [];

public showCheckboxes() {
        let checkboxes = document.getElementById("checkboxes");
        if (!this.expanded) {
          checkboxes.style.display = "block";
          this.expanded = true;
        } else {
          checkboxes.style.display = "none";
          this.expanded = false;
        }
      }

    public myFunction(selectedBase) {
        this.selectedBaseLicences.push(selectedBase)
    }

I'm trying to display the checked base in Select as an array but template is not getting updated after this.selectedBaseLicences.push(selectedBase) operation. How to update the template in this case?

What the push method of Array really does is append another object to the existing array (with no reference change) and Angular change detection only checks objects identity.

What you can do is to copy the array after each update using slice method which returns a new array.

 public myFunction(selectedBase) {
        this.selectedBaseLicences.push(selectedBase);
       this.selectedBaseLicences= this.selectedBaseLicences.slice()
    }

or you could use Spread syntax

 public myFunction(selectedBase) {
                this.selectedBaseLicences.push(selectedBase);
               this.selectedBaseLicences= [...this.selectedBaseLicences]
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM