0

It is getting really annoying! I have an array of objects i found this solution: How to use select/option/NgFor on an array of objects in Angular2

but after all I am doing the same as this but if i log my $event it is undefined.. probably because it is stringified but after that not parsed back.

Here is an example of my code:

<div class="container">
<div class="row" *ngFor="#condition of conditions;#conditionindex = index">
    <div class="col-xs-3">
        <select class="form-control" [ngModel]="stringify(condition)" (ngModelChange)="onChange(conditionindex, $event)">
            <option *ngFor="#c of catalog;#catalogindex = index" [value]="stringify(c)">
                {{c.name}}
            </option>
        </select>
    </div>
    <condition-detail [condition]="condition"></condition-detail>
</div>

<a class="btn btn-primary" (click)="newCondition()"><i class="glyphicon glyphicon-plus"></i></a>

And this is the component code:

export class ConditionBuilderComponent implements OnInit {
conditions: Condition[] = [];
catalog: Condition[] = [];

constructor(public _conditionService: ConditionService) { }

getConditions() {
    this._conditionService.getConditions().then(conditions => this.catalog = conditions);
}

ngOnInit() {
    this.getConditions();
}

stringify(o:any): string {
    return JSON.stringify(o);
}

onChange(conditionsIndex, selectedCondition:string): void {
    console.log(typeof selectedCondition);
    //JSON.parse(selectedCondition);
    console.log(selectedCondition);
    //this.conditions[conditionsIndex] = this.catalog[condition];
    console.log(typeof selectedCondition);
}

Please help me out. The console log of selectedCondition is undefined.

Community
  • 1
  • 1
Sireini
  • 4,142
  • 12
  • 52
  • 91

2 Answers2

2

With the latest Angular2 version (beta 14), support for choose as object has been added.

uksz
  • 18,239
  • 30
  • 94
  • 161
1

Got it allready:)

Here the solution:

<select class="form-control" [ngModel]="condition.name" (ngModelChange)="onChange(conditionindex, $event)">
   <option *ngFor="#c of catalog;#catalogindex = index" [value]="c.name">
                {{c.name}}
   </option>
</select>

And the component file:

  onChange(conditionsIndex, selectedCondition:string): void {
    this.conditions[conditionsIndex] = this.catalog.find(condition => condition.name == selectedCondition);
}
Sireini
  • 4,142
  • 12
  • 52
  • 91