Angular5中如何在ng2-select展示客户列表并获取选中ID?
I'll walk you through fixing this step by step to get your ng2-select component working as expected—showing the client's full name and capturing the selected ID.
Step 1: Prepare Your Client Data with Full Name
First, we need to modify the client data to include a combined full name field, since ng2-select needs a single property to display as the option label. Update your clientList method in project.component.ts to add a fullName property to each client:
import {Component, OnInit, ViewChild} from '@angular/core'; import {ActivatedRoute, Router} from '@angular/router'; import {ProjetService} from '../../../../../service/projet.service'; import {Projet} from '../../Models/Projet'; import { ModalDirective } from 'ngx-bootstrap/modal'; import 'rxjs/add/operator/map'; import {ClientService} from '../../../../../service/client.service'; @Component({ selector: 'app-projects', templateUrl: './projects.component.html', styleUrls: ['./projects.component.scss'] }) export class ProjectsComponent implements OnInit { // Initialize as empty array to avoid template errors listClients: any[] = []; // Variable to store the selected client ID selectedClientId: number; constructor( private router: Router, private projetSevice: ProjetService, private clientServ: ClientService, private route: ActivatedRoute ) { } ngOnInit() { this.doSearch(); this.clientList(); } clientList(){ this.clientServ.getListClients() .subscribe((data: any)=>{ // Map each client to add a fullName property this.listClients = data.map(client => ({ ...client, fullName: `${client.firstname} ${client.lastname}` })); },err=>{ console.log('this is error '); }) } public selected(value: any): void { this.selectedClientId = value; console.log('Selected client ID: ', value); } public removed(value: any): void { this.selectedClientId = null; console.log('Removed value is: ', value); } public typed(value: any): void { console.log('New search input: ', value); } public refreshValue(value: any): void { this.selectedClientId = value; } }
Step 2: Update the ng2-select Template
Now, bind the modified client data to your ng2-select component in project.component.html. We'll use bindLabel to specify the full name as the display text, bindValue to set the ID as the selected value, and add two-way binding with ngModel to track the selected ID:
<div class="form-group row"> <label class="col-sm-5 col-form-label">To select a client : </label> <div class="col-sm-6"> <ng-select [allowClear]="true" [items]="listClients" bindLabel="fullName" bindValue="id" (selected)="selected($event)" (removed)="removed($event)" (typed)="typed($event)" placeholder="select a client" [(ngModel)]="selectedClientId" > </ng-select> </div> </div>
Step 3: Ensure ng2-select is Imported in Your Module
Don't forget to import the ng2-select module in your app module (or the module containing ProjectsComponent):
import { NgSelectModule } from 'ng2-select'; @NgModule({ imports: [ // ... other imports NgSelectModule ], // ... declarations, providers, etc. }) export class YourModuleName { }
How It Works
bindLabel="fullName": Tells ng2-select to display thefullNameproperty (firstname + lastname) in the dropdown options.bindValue="id": Sets the value emitted by the select component to the client'sidproperty, so yourselectedmethod receives the ID directly.[(ngModel)]="selectedClientId": Creates two-way binding between the select component and your component'sselectedClientIdvariable, so you can easily access the selected ID anywhere in your component logic.
Now when you run your app, the dropdown will show each client's full name, and selecting an option will store the client's ID in selectedClientId for you to use in your component.
内容的提问来源于stack exchange,提问作者dEs12ZER

