Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: How to handle *ngif in option select

Tags:

angular

How to can i use *ngif for set a specific default selected option?

I need reload data from database for editing, when i retrieve data i need set the default value of option in base a stored value.

I have this:

<select class="form-control" id="deviceModel">
        <option value="">Select a category</option>
        <option *ngFor='let element of category'*ngIf="{{element}}==={{nameDevice}}" value="{{element}}">{{element}}</option>    
    </select>

Thanks in advance.

like image 816
BryGom Avatar asked Nov 25 '16 03:11

BryGom


3 Answers

ngIf is for structural manipulation, basically whether something is in the DOM, or removed. If you want to bind to the selected property, you could use:

<select class="form-control" id="deviceModel">
    <option value="">Select a category</option>
    <option *ngFor='let element of category' [selected]="element === nameDevice" [value]="element">{{element}}</option>    
</select>

From https://angular.io/docs/ts/latest/api/forms/index/SelectControlValueAccessor-directive.html:

If your option values are simple strings, you can bind to the normal value property on the option. If your option values happen to be objects (and you'd like to save the selection in your form as an object), use ngValue instead.

If you want to use ngModel binding, have a look at Binding select element to object in Angular 2

Note that when using property binding, you don't/shouldn't use string interpolation

like image 153
Fiddles Avatar answered Oct 22 '22 01:10

Fiddles


I would recommend you to do it in the ts or js file depends on you are using typescript or javascript.

I assume when you load data from the database by sending an ajax request to the API? Use ngModel to bind the data (selectedValue in this case) in template

<select [(ngModel)]="selectedValue">
  <option *ngFor="let c of category" [ngValue]="c">{{c.name}}</option>
</select>

and set

this.selectedValue = response.value;

in the call back function.

like image 3
Tim Hong Avatar answered Oct 22 '22 01:10

Tim Hong


<select class="form-control"> <option *ngFor="let area of areaData" value="{{area.id}}" [selected]="area.id == userData.area_id"> {{area.area_name}} ({{area.area_pin}}) </option> </select>

Use [selected] for dynamic selection field in Angular 4.

like image 3
Vivek Singh Avatar answered Oct 22 '22 00:10

Vivek Singh