0

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??

Manu Mohan
  • 1,694
  • 2
  • 20
  • 31
  • You're not setting `this.frm` anywhere other than when you do `this.frm={}`, so it will always be an empty object – user184994 Aug 05 '18 at 08:24
  • You cannot bind a dynamic value to ngModel, if I am able to understand you correctly. You can probably use `(change)` event to pass the object `c` and then dynamically access / assign value to the required field. – Ankit Sharma Aug 05 '18 at 08:26
  • Yea, I think so. A small change done, and its working now. Ill post it as answer – Manu Mohan Aug 05 '18 at 08:37
  • I think you should take in account reactive formArray far better approach imo https://angular.io/api/forms/FormArray - a simple example https://alligator.io/angular/reactive-forms-formarray-dynamic-fields/ – Whisher Aug 05 '18 at 08:49
  • You cannot bind dynamic value to ngModel – Rashmi Kumari Aug 05 '18 at 09:04

1 Answers1

0

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

Manu Mohan
  • 1,694
  • 2
  • 20
  • 31