Reputation: 638
Hi I am having an select box in my angular ui . I am populating it with some values when the component loads . I want to make the first item selected by default, however it not happening. not sure what is wrong with my code.
CdrMessageStatus
export enum CdrMessageStatus {
ENROUTE = 'ENROUTE',
DELIVERED = 'DELIVERED',
EXPIRED = 'EXPIRED',
UNDELIVERABLE = 'UNDELIVERABLE'
}
MessageHistoryComponent
export class MessageHistoryComponent implements OnInit {
cdrStatuses = CdrMessageStatus;
cdrStatusKeys: any[];
ngOnInit() {
this.formGroup = this.fb.group({
range: [ [ ], Validators.required],
cdrStatus: [],
msisdn:[''],
campaign: [],
inventory: [],
flight: []
}
);
combineLatest(this.campaignsService.getStatuses(),this.authenticationService.currentUser$, of(this.authenticationService.authority),
this.flightsService.getStatuses()
).subscribe(([campaignStatuses,user,authority,flightStatuses]) => {
this.cdrStatusKeys = Object.keys(this.cdrStatuses);
}
}
message-history.component.html
<div class="col-2">
<select class="custom-select" formControlName="cdrStatus">
<option [value]="" [selected]="selected" disabled>{{ 'LABELS.CDR_STATUS' | translate }}</option>
<option *ngFor="let key of cdrStatusKeys" [value]="key"> {{ cdrStatuses[key] }} </option>
</select>
</div>
also attaching a screenshot below
I can see the values populated. 'ENROUTE','DELIVERED','EXPIRED','UNDELIVERABLE' however i want to select the item by default
<option [value]="" [selected]="selected" disabled>{{ 'LABELS.CDR_STATUS' | translate }}</option>
appreciate any help
Upvotes: 1
Views: 94
Reputation: 9355
Set the first value for the Select element in the TS:
this.formGroup.get('cdrStatus').setValue(object);
Upvotes: 2
Reputation: 4076
You problem is that the default option needs a value, without it, it doesn't show as a default option:
<select class="custom-select" formControlName="cdrStatus">
<option [value]="null" [selected]="selected" disabled>{{ 'LABELS.CDR_STATUS' | translate }}</option>
<option *ngFor="let key of cdrStatusKeys" [value]="key"> {{ cdrStatuses[key] }} </option>
</select>
Upvotes: 3
Reputation: 527
Currently, you have value = ""
<option [value]=""
You can set this to the first value. Hard coded.
<option [value] ='ENROUTE'
If you want dynamic:
Check this out: Angular Material md-select default selected value
You can use two-way data binding:
this.selectedOption = '1';
HTML:
<mat-select [(ngModel)]="selectedOption">
<mat-option value="1">One</mat-option>
<mat-option value="2">Two</mat-option>
</mat-select>
Upvotes: 2