Angular ng-select如何获取用户输入值及bindLabel值?
解决Angular ng-select获取输入文本值的问题
问题原因
你当前的事件绑定未传递正确参数,且keydown/keyup并非ng-select推荐的监听输入文本的方式;同时点击创建按钮时未关联输入框内容,导致val始终为undefined。
解决方案
1. 用ng-select内置(search)事件监听输入文本
ng-select提供了专门的(search)事件,可实时返回用户输入的搜索文本,替换你当前的键盘事件:
修改模板代码:
<ng-select #brandSelect placeholder="{{'HtmlElement.DropDownNoSelected' | translate}}" [items]="brands" bindLabel="brandName" bindValue="brandId" id="brandId" name="brandId" formControlName="brandId" (change)="brandTyped($event)" (search)="onSearch($event)"> <ng-template ng-footer-tmp> <p class="create-new" (click)="createNewBrand()">Create New {{TEXT_VALUE}}</p> </ng-template> </ng-select>
组件中新增对应方法:
onSearch(searchTerm: string) { console.log("输入的品牌文本:", searchTerm); // 可将搜索文本存入组件变量,方便后续创建使用 // this.newBrandName = searchTerm; }
2. 点击创建按钮时获取输入文本
通过模板引用变量#brandSelect结合ViewChild获取ng-select实例,提取当前输入的文本:
首先在组件中导入并声明ViewChild:
import { Component, ViewChild } from '@angular/core'; import { NgSelectComponent } from '@ng-select/ng-select'; @Component({ // 组件元数据 }) export class YourComponent { @ViewChild('brandSelect') brandSelect!: NgSelectComponent; newBrandName: string = ''; createNewBrand() { this.newBrandName = this.brandSelect.searchTerm; console.log("要创建的新品牌名称:", this.newBrandName); // 此处可调用后端接口,传递this.newBrandName完成创建 } }
3. 优化选中已有品牌的逻辑(可选)
(change)事件会返回选中的选项对象,可修改方法获取选中品牌的信息:
brandTyped(selectedItem: any) { if (selectedItem) { console.log("选中的品牌ID:", selectedItem.brandId); console.log("选中的品牌名称:", selectedItem.brandName); } }
关键说明
(search)事件是ng-select专为监听搜索输入设计的事件,比原生键盘事件更可靠,会自动过滤方向键等无效输入。NgSelectComponent的searchTerm属性存储了输入框当前的文本内容,即使无匹配选项也能正常获取。- 确保已在Angular模块中正确导入
NgSelectModule。
内容的提问来源于stack exchange,提问作者J.C
相关产品推荐
相关产品推荐

