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.
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
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.
<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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With