Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 select initial object with ngValue

Tags:

angular

I'm trying to set an initial value when filling a select, the data is coming from rest and loaded in the component. The initial value is not set/updated after the

Getting the list to fill the select:

...
ngOnInit():any {

this.crudService.get(`/api/countries`).subscribe(data => {this.countries = data;});
...

Getting the model object witch has a Country:

...
this.crudService.get('/api/unions/default').subscribe(data => {
 this.union = data;
...

HTML:

...
<div class="col-md-2">
              <select *ngIf="union.country" [(ngModel)]="union.country" class="form-control">
                <option *ngFor="let c of countries" [ngValue]="c">{{c.code}}</option>
              </select>
            </div>

...

Everything works, I can select a country and it is correctly updated in the model but the initial value is not selected but existing in the model... Any suggestions or is this a bug?

Thanks!

like image 687
fleske Avatar asked Jun 09 '16 14:06

fleske


1 Answers

If the default value is assigned to union.country and it is an object (vs a primitive value), it needs to be the same instance, not only an object with the same content.

like image 72
Günter Zöchbauer Avatar answered Nov 03 '22 12:11

Günter Zöchbauer