问题
I have a data like this.
[
{
"user_id": 1,
"name": "John"
},
{
"user_id": 2,
"name": "Doe"
},
...
]
In app, I have set two dropdown for show only user_id and name respectively.
For user id I have used simple select
and option
.
For name
I have used ngx-select-dropdown
.
Now I have to make two way binding, when I select Doe
then id dropdown 2
will automatically bind. Same way if I choose id 1
then John
will autimatically select.
I have a design like below.
回答1:
To dynamically generate a drop-down list, based on the data above, create a model.
User-model.ts
export class UserModel {
user_id: number;
name: string; }
In the component, it would look something like this
import { UserModel } from '../app/model/user-model';
curr_name: string = '';
curr_user_id: number = null;
users: UserModel[] =
[
{
"user_id": 1,
"name": "John"
},
{
"user_id": 2,
"name": "Doe"
}];
getName(id: any): void {
if (id !== 'SELECT') { // SELECT is used for default here
this.curr_name = this.users.find(x => x.user_id == id).name;
}
}
getUserId(name: any): void {
if (name !== 'SELECT') {
this.curr_user_id = this.users.find(x => x.name == name).user_id;
}
}
And lastly, based on the your design, the HTML code would essentially look like
<select (change)="getName($event.target.value)">
<option>SELECT</option>
<option *ngFor="let user of users" [ngValue]="user.user_id"
[selected]="user.user_id === curr_user_id">
{{user.user_id}}
</option>
</select>
<select (change)="getUserId($event.target.value)">
<option> SELECT</option>
<option *ngFor="let user of users" [ngValue]="user.name"
[selected]="user.name === curr_name">
{{user.name}}
</option>
</select>
Though since you are updating both drop-downs regardless why not create only one dropdown and have the user-id
and name
in a list format so you wouldn't need to keep updating each other.
回答2:
I have solved my issue with the help of reactive form group
. It provides me value easily and I have set it's form value with the help of patchValue()
feature. And it works fine for me.
来源:https://stackoverflow.com/questions/53864392/how-to-set-two-way-binding-data-in-dropdown-in-angular-6