Angular实现用户搜索功能:替换下拉框为搜索输入与按钮
实现用户搜索功能(替换下拉框为输入框+搜索按钮)
当前代码
组件初始化逻辑
ngOnInit() { this.getUsers(); } getUsers() { this.http.get<User[]>("https://graph.microsoft.com/v1.0/users") .subscribe(users => { console.log(users); this.users = users; }); }
页面模板代码
<p-dropdown [options]="users" optionLabel="displayName" [showClear]="true" placeholder="选择用户"></p-dropdown>
需求
- 将下拉框替换为输入框和搜索按钮,用户输入文本后点击搜索按钮,调用带
startsWith查询参数的API重新获取用户数据
目标页面模板示例
<input pInputText type="text" placeholder="搜索用户" class="w-full"/> <p-button label="搜索"></p-button>
修改后的完整实现
组件逻辑(TypeScript)
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; interface User { displayName: string; // 按需补充其他用户属性 } @Component({ selector: 'app-user-search', templateUrl: './user-search.component.html' }) export class UserSearchComponent implements OnInit { users: User[] = []; searchKeyword: string = ''; constructor(private http: HttpClient) { } ngOnInit() { this.getUsers(); // 初始化加载全部用户,也可留空 } getUsers(keyword?: string) { let apiUrl = 'https://graph.microsoft.com/v1.0/users'; // 拼接startsWith过滤条件(Microsoft Graph API使用$filter语法) if (keyword?.trim()) { apiUrl += `?$filter=startsWith(displayName,'${encodeURIComponent(keyword.trim())}')`; } // Microsoft Graph返回的用户数据在value字段中 this.http.get<{value: User[]}>(apiUrl) .subscribe(res => { this.users = res.value; console.log('用户数据:', this.users); }); } onSearch() { this.getUsers(this.searchKeyword); } }
修改后的页面模板(HTML)
<!-- 搜索输入框与按钮 --> <input pInputText type="text" placeholder="搜索用户" class="w-full" [(ngModel)]="searchKeyword" /> <p-button label="搜索" (click)="onSearch()"></p-button> <!-- 搜索结果展示 --> <div class="mt-3" *ngIf="users.length > 0"> <h5>搜索结果</h5> <ul> <li *ngFor="let user of users">{{ user.displayName }}</li> </ul> </div>
注意事项
- 确保你的应用已获得Microsoft Graph API的User.ReadBasic.All或更高权限,否则会返回权限错误
- 使用
encodeURIComponent处理搜索关键词,避免特殊字符破坏API请求格式 - 模板中使用
[(ngModel)]需要在对应模块中导入FormsModule
内容的提问来源于stack exchange,提问作者Wicked
相关产品推荐
相关产品推荐

