I have run into an issue in pre-selecting values on a dropdown list in Angular 2.
I set an array of colours in the component which I bind successfully to the drop
This works for me.
<select formControlName="preferredBankAccountId" class="form-control" value="">
<option value="">Please select</option>
<option *ngFor="let item of societyAccountDtos" [value]="item.societyAccountId" >{{item.nickName}}</option>
</select>
Not sure this is valid or not, correct me if it's wrong.
Correct me if this should not be like this.
It may help someone as I need to only show selected value, don't need to declare something in component and etc.
If your status is coming from the database then you can show selected value this way.
<div class="form-group">
<label for="status">Status</label>
<select class="form-control" name="status" [(ngModel)]="category.status">
<option [value]="1" [selected]="category.status ==1">Active</option>
<option [value]="0" [selected]="category.status ==0">In Active</option>
</select>
</div>
Setting car.colour
to the value you want to have initially selected usually works.
When car.colour
is set, you can remove [selected]="car.color.id == x.id"
.
If the value is not a string [ngValue]="..."
must be used. [value]="..."
only supports strings.
Actually if You use ReactiveForms i found this way much easier to acomplish:
If the form is defined like this:
public formName = new FormGroup({
fieldName: new FormControl("test") //where "test is field default value"
});
Then thats the way You can change its value:
this.formName.controls.fieldName.setValue("test 2"); //setting field value to "test 2"
If your values are coming from the database, show selected values in that way.
<div class="form-group">
<label for="status">Status</label>
<select class="form-control" name="status" [(ngModel)]="category.status">
<option [value]="1" [selected]="category.status ==1">Active</option>
<option [value]="0" [selected]="category.status ==0">In Active</option>
</select>
</div>
<select formControlName="preferredBankAccountId" class="form-control">
<option *ngFor="let item of societyAccountDtos" [value]="item.societyAccountId" >
{{item.nickName}}
</option>
</select>
In the Component:
this.formGroup.patchValue({
preferredBankAccountId: object_id_to_be_pre_selected
});
You can also give this value where you initialize your formGroup or later,depending on your requirement.
You can do this by using [(ngModel)] binding also where you don't have to initialize your formControl.
<select [(ngModel)]="matchedCity" formControlName="city" class="form-control input-sm">
<option *ngFor="let city of cities" [ngValue]="city">{{city.cityName}}</option>
</select>
Here, matchedCity is one of object within cities.