There are several questions about this and different answers but none of them really answers the question. So again:
Setting default of a Dropdown select by value isn't working in my case. Why? This is from the dynamic Form tutorial of Angular 4:
<select [id]="question.key" [formControlName]="question.key"> <option *ngFor="let opt of question.options" [value]="opt.key" [selected]="opt.selected">{{opt.selected+opt.value}}</option> </select>
It doesn't select anything. Available options are:
But static true:
<option ... [selected]="true">...</option>
selects the last value (all true). It also works with a private variable boolvar = true
and using it in [selected]="boolvar"
I don't understand the difference between the "opt" object and the class variable.
Short Answer : use [selected]="isSelected" in your option tag!
Overview. HTML select element with AngularJS data-binding. The select directive is used together with ngModel to provide data-binding between the scope and the <select> control (including setting default values). It also handles dynamic <option> elements, which can be added using the ngRepeat or ngOptions directives.
Use unique identifiers as values for dropdown options, which in your case is category ids. Now pass the category id from the portal object to ngModel directive to bind the value to dropdown. You can use ngModelChange directive to listen for category id value changes and update the same in portal object.
If you want to select a value based on true / false use
[selected]="opt.selected == true"
<option *ngFor="let opt of question.options" [value]="opt.key" [selected]="opt.selected == true">{{opt.selected+opt.value}}</option>
checkit out
Angular 2 - Setting selected value on dropdown list
Here is my example:
<div class="form-group"> <label for="contactMethod">Contact method</label> <select name="contactMethod" id="contactMethod" class="form-control" [(ngModel)]="contact.contactMethod"> <option *ngFor="let method of contactMethods" [value]="method.id">{{ method.label }}</option> </select> </div>
And in component you must get values from select:
contactMethods = [ { id: 1, label: "Email" }, { id: 2, label: "Phone" } ]
So, if you want select to have a default value selected (and proabbly you want that):
contact = { firstName: "CFR", comment: "No comment", subscribe: true, contactMethod: 2 // this id you'll send and get from backend }
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