Reputation:
Why ngModel
is creating blank element in HTML - select - option? How can I get rid of this?
First code.
<div style="text-align: center;">
<label for="sel1">Select list (select one):</label>
<select class="form-control" id="sel1" style="height: 3rem; width: max-content; margin-left: 33.5rem;" (change)="getSelectedUserAccess()">
<option>suman</option>
<option selected>rony</option>
<option>alex</option>
</select>
</div>
Screenshot:
Second code [wrong]
<div style="text-align: center;">
<p>Select User : </p>
<select [(ngModel)]="currentSelectedUser" class="form-control" id="userSelect1"
style="height: 3rem; width: max-content; margin-left: 33.5rem;" (change)="getSelectedUserAccess()">
<option>suman</option>
<option selected>rony</option>
<option>alex</option>
</select>
</div>
screnshot :
Upvotes: 0
Views: 1572
Reputation: 506
You need to initialize ngModel value with the value from database or 'rony'. Also maintain an array for list of users so that you can show the selectedCurrentUser as the selected user by default using [selected]="currentSelectedUser===user"
.
html:
<div style="text-align: center;">
<p>Select User : </p>
<select [(ngModel)]="currentSelectedUser" class="form-control" id="userSelect1"
style="height: 3rem; width: max-content; margin-left: 33.5rem;"
(change)="getSelectedUserAccess()">
<option *ngFor="let user of users" [selected]="currentSelectedUser === user">
{{user}}
</option>
</select>
</div>
ts:
users:Array<string>=['suman', 'alex', 'rony'];
currentSelectedUser:string;
constructor(private usrService:UserService){ }
ngOnInit(){
this.currentSelectedUser = this.usrService.getCurrentUser(); //rony
}
getSelectedUserAccess(){
console.log("Current Selected User", this.currentSelectedUser)
}
Upvotes: 2