1

I have ecountered a problem while trying to set the selected value in dropdown to equal value taken from my model object. Some explanations:

sourceSchemesList is of type Scheme[]

element contains property named scheme of type Scheme

Scheme looks like below:

{
  name: string
  packetName: string
  packetVersion:
    {
      minor: number
      major: number
    }
}

When opening a page, first I initialize the select options' list and after that, I set value for currentSource.operations, with valid data. When opening a view, the dropdowns appear with correct options, but there is no selected value.

<div class="row" *ngFor='let element of currentSource.operations'>
    <div class="col-md-10">
        <select class="form-control col-sm-12" [(ngModel)]="element.scheme">
            <option *ngFor="let row of sourceSchemesList" [ngValue]="row" [label]="row.packetName + ' : ' + row.name"></option>
        </select>
    </div>
    <div class="col-md-2">
        <button type="button" class="btn mini-button border-0 p-1" (click)="deleteSourceOperation(element)">
            <i class="fa fa-minus" aria-hidden="true"></i>
        </button>
    </div>

I have tried using [selected] attribute and setting the condition to

  "element.scheme.name===row.name && element.scheme.packetName===row.packetName && <comparing versions by every property>"

but it did not help. What else could interfere? May the problem exist because of that my ngModel is an array' object?

Edit: The objects are different, so they do not equal by references. This is why I wanted to use [selected].

aynber
  • 22,380
  • 8
  • 50
  • 63
DiSaSter
  • 11
  • 3
  • Is the `element.scheme` the same object as the `row` in `sourcesSchemesList`? By beign the same I mean, it is the same reference, not another object created with the same properties and values. – klauskpm Apr 05 '18 at 12:24
  • It is not, I know that Angular compares references, this is why I thought adding [selected] is the solution. – DiSaSter Apr 05 '18 at 12:44

1 Answers1

1

The ngModel and the option element need to be the same reference. Have a look at this stackblitz:

https://stackblitz.com/edit/angular-dphu6f

The directly referenced select works the other one doesnt. Angular does not compare every property of an object to define if it is the same, it checks the reference of the object.

You can supply a compareWith function on the select tag to override the default comparison of Angular.

Shadowlauch
  • 581
  • 1
  • 5
  • 13
  • I know that Angular compares references, this is why I thought adding [selected] is the solution. This blitz seems to be empty – DiSaSter Apr 05 '18 at 12:44
  • works perfect! I already had implemented some comparison method, so just renamed the example and it runs perfectly – DiSaSter Apr 06 '18 at 07:17