Search code examples
angularangular6ngforngmodel

Dynamic ngModel inside ngFor not working


I've view page like below

    <div class="row" *ngFor="let c of conditionArray;>
        <div class="col-sm-12 col-xl-2 m-b-10">
            <ng-select [(ngModel)]="c.condition" placeholder="Select Condition" [ngClass]="'ng-select'" [options]="conditions" [multiple]="false">      </ng-select>
        </div>
   </div>

And my component is like below

this.frm={};
conditionArray:Array<any> =
[
    {
      condition:'frm.condition1',
      pos:1
    }
]
saveCond(){
    alert(JSON.stringify(this.frm));
}

When I call saveCond() method, its always displaying empty object. But if i rewrite my HTML model to have [(ngModel)]="frm.condition1" , then its working fine. What am I doing wrong here??


Solution

  • I did a small change and now its working fine!. Instead of passing entire model (frm.condition1), I changed it to pass just inner model name alone. Like below,

        conditionArray:Array<any> =[
        {
          condition:'condition1',
          pos:1
        }
      ]
    

    And from my HTML, I pushed model into 'frm' object as,

    [(ngModel)]="frm[c.condition]"
    

    Now I'm able to access 'frm' object