Set default select list value Angular2

我的梦境 提交于 2019-12-02 06:17:33

If you use [ngValue] then you need to assign the identical object instance to exampleArray. Another object instance with the same properties and values won't do.

If you use [value]="..." instead of [ngValue], then only strings can be used and for string comparison to different string instances containing the same characters are considered equal, but that's not the case for object instances where exampleArray needs to reference the exact same object reference used with [ngValue].

Actually

[(ngModel)]="exampleArray"

in your example is invalid, because the model should not be the array that is used to generate the <option> elements, it should be a property that holds the selected value.

   <div class="form-group">
        <label class="col-md-4 control-label" for="CustomFix">Select an option:</label>
        <div class="col-md-4">
            <select id="example" name="example" class="form-control" [(ngModel)]="selectedItem" (ngModelChange)="changes()">
                <option disabled selected>Select a Custom Fix</option>
                <option *ngFor="let example of exampleArray" [ngValue]="example">{{example.attribute }}</option>
            </select>
        </div>
    </div>
constructor() {
  this.selectedItem = exampleArray[1]; // will make the 2nd element of `exampleArray` the selected item
}

If you want to have this option selected at the start - that's usually when the ngModel's value is undefined, you just have to tell Angular that this option is responsible for undefined value, so it should be:

<option disabled [ngValue]="undefined">Select a Custom Fix</option>

You also need do correct your [(ngModel)] binding - right now you're trying to bind selected value to.. the array itself. You should rather bind to some other property, e.g.:

<select id="example" name="example" class="form-control" [(ngModel)]="example">

(You can see the working solution here: http://plnkr.co/edit/Zu29ztqaaDym1GYDAhtJ?p=preview)

You should give that option a value, bind the select element to an ID variable, and set that variable on component load.

// controller
exampleArraySelectedValue = -1;
<div class="form-group">
  <label class="col-md-4 control-label" for="CustomFix">Select an option:</label>
  <div class="col-md-4">
    <select id="example" name="example" class="form-control" [(ngModel)]="exampleArraySelectedValue" (ngModelChange)="changes()">
      <option value="-1">Select a Custom Fix</option>
      <option *ngFor="let example of exampleArray" [ngValue]="example">{{example.attribute }}</option>
    </select>
  </div>
</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!