Search code examples
angularloopsngmodel

How can I do a ngModel in a loop?


I have an issue in my angular application I want to change the value of ngModel if the item is in the license but I'm in a loop in my .ts file I think the ngModel take the last value of test but some items are not in the license I want to put the value of ngModel to false.

.html file :

<div *ngFor="let elt of element">

    <input type="checkbox" #checkbox class="input_checkbox" [ngModel]="test" name="itemBoolean_{{elt.item.id}}" id="custom_item_{{elt.item.id}}" >

</div>

.ts file :

 element : item[];

 itemInLicense : ItemLicense[];

 test : boolean = false ;


ngOnInit() {

    this.itemInLicense.forEach((elt)=>{

        if(document.getElementById("custom_item_"+elt.itemId))

            this.test = true ;

        else

            this.test = false ;

     })

}

Solution

  • You can use the index number in the iteration if the variable you bind is an Array as well:

    Then you need to change property test as follows:

     test : boolean[] = [] ;
    
     ngOnInit() {
    
       this.itemInLicense.forEach((elt, index)=>{
         if(document.getElementById("custom_item_"+elt.itemId)){
           this.test[index] = true ;
        } else {
          this.test[index] = false ;
        });
     }
    

    And adapt the HTML as here:

    <div *ngFor="let elt of element; i=index">
      <input type="checkbox" 
             #checkbox 
             class="input_checkbox"
             [ngModel]="test[i]"
             name="itemBoolean_{{elt.item.id}}"
             id="custom_item_{{elt.item.id}}" >
    
    </div>