I am building a reactive form in angular 7, and what I want to do is: 1. Select an user from the 'Name' dropdown list; 2. Automatically show the username that belongs to that user, under the 'Username' section (image); 3. When I submit the form, I want to send only the id of the user that was selected.
My current approach works for steps 1 & 2, the only problem that I have now is that to [ngValue] I bind the object "user" instead of just the id, which results in me submitting all the details of the user in the end, instead of just the id. Also apparently I should stop using ngModelChange on reactive forms.
I am not sure if there is a way around this. If I use the "user.id" as value, I cannot reach the username anymore (or other details of the user).
I saw some examples with ngModel and ngModelChange, but according to the angular doc, 'Support for using the ngModel input property and ngModelChange event with reactive form directives has been deprecated in Angular v6 and will be removed in Angular v7.'
For the data I am using this
html
<form class="form" [formGroup]="addUser" (ngSubmit)="onSubmit()">
<div class="row">
<div class="col-3">
<div class="form-group">
<label for="username">Username:</label>
<p>{{selectedUser.username}}</p>
</div>
</div>
<div class="col-9">
<div class="form-group">
<label for="name">Name:</label>
<select class="form-control" formControlName="name" (ngModelChange)="selectUser($event)">
<option *ngFor="let user of users" [ngValue]="user">{{ user.name }}</option>
</select>
</div>
</div>
</div>
</form>
ts
public selectedUser = {};
...
selectUser(user){
this.selectedUser = user;
}
change
event on the<select>
. I don't pass$event
as an argument, the selected option value is available from theFormControl
assigned to the<select>
. – The Head Rush