使用Angular 12 Material UI实现自动完成功能
自动完成是一种服务,当终端用户输入某些关键词或将光标放在输入框上时,会向他们显示推荐的选项。
实现自动完成服务是相对简单的。唯一需要做的是调用getItems 方法。
然后我们使用选择框来自动显示从服务器上检索的项目。
本教程将帮助你学习如何在Angular 12中使用Material UI元素实现自动完成。
前提条件
要跟上本教程,你需要。
- 一些JavaScript的基本知识。值得注意的是,Angular使用TypeScript语言。然而,在本教程中,它是不必要的。
- 有关Angular和Material UI的基本知识。
- Angular CLI 12要在本地安装。
- 安装一个IDE,如Webstorm。
教学目的
本教程将帮助读者了解Angular Material过滤引擎。最后,你将能够从远程服务器检索数据。
当用户开始输入时,这些数据就可以自动显示在自动完成组件中。
设置项目
为了设置一个Angular应用程序,我们使用以下命令。
ng new autocomplete
接下来,cd ,进入项目文件夹,安装angular material 。
cd autocomplete
ng add @angular/material
当上述命令被执行时,它会提示你选择一个Angular预置的主题,如下图所示。
? Choose a prebuilt theme name, or "custom" for a custom theme: Indigo/Pink
❯ Indigo/Pink [ Preview: https://material.angular.io?theme=indigo-pink ]
Deep Purple/Amber [ Preview: https://material.angular.io?theme=deeppurple-amber ]
Pink/Blue Grey [ Preview: https://material.angular.io?theme=pink-bluegrey ]
Purple/Green [ Preview: https://material.angular.io?theme=purple-green ]
在本教程中,我们将使用默认配置。
Angular Material配置
现在我们已经完全配置了我们的应用程序,让我们继续并配置我们的项目以使用自动完成模块。
首先,在项目根部创建material.module.ts 文件,然后编辑该文件,如下图所示。
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
const materialModule = [
...
MatAutocompleteModule,
... // these are modules skipped for this article
];
@NgModule({
imports: [
CommonModule,
...
],
exports: [
...
materialModule
],
})
export class MaterialModule { }
在上面的代码中,我们从Angular material 中导入了普通模块和MatAutocompleteModule 。
接下来,我们为新导入的模块创建一个array ,以确保我们导入这个模块时它是可用的。
现在我们的材料模块已经准备好了,让我们把它导入到app.module.ts 文件中,如下图所示。
// Import the angular material
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MaterialModule } from './angular-material.module';
...
@NgModule({
declarations: [...],
imports: [
...
MaterialModule,
],
providers: [...],
bootstrap: [...],
schemas: [...]
})
export class AppModule { }
在上面的模块中,我们只让Angular材质在我们的应用程序中可用。
注意,我们正在使用app.module.ts 作为根模块。因此,所有其他模块都将在这个文件中注册。
当我们重新执行我们的应用程序时,我们的Angular Material就可以使用了。
设置API服务
在上一节中,我们设置了我们的material.module.ts 模块并在material.module.ts 文件中注册了MatAutocompleteModule 。
让我们用以下步骤来设置我们的API服务。
首先,通过运行下面的命令创建一个API服务。
ng g service api
上述命令创建了一个src/app/api.service.ts 。我们将使用这个服务从远程服务器检索数据。
建议将所有的API请求放在一个服务文件中,尤其是在Angular中构建大型应用程序时。这有助于管理和扩展应用程序。
如下图所示编辑该文件,向远程服务器发出HTTP请求。
// importing the default angular config files
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
// inject the project
@Injectable({
providedIn: 'root'
})
export class ApiService {
private BASE_URL = "http://localhost:8000/api/v1/";
constructor(private httpClient: HttpClient) { }
// a GET request to retrieve list of articles
getArticles():Observable<Article>{
return this.httpClient.get<Article>(`${this.BASE_URL}articles`);
}
// a post request to add an article
addArticles(article:Article):Observable<Article>{
return this.httpClient.post<Article>(`${this.BASE_URL}articles`,article);
}
}
在上面的代码中,我们从@angular/common/http 中导入了HTTP客户端,并指定了我们的远程服务器基本URL。
接下来,我们使用依赖注入将HTTP客户端注入到一个构造器中。
依赖注入,俗称DI,允许我们在整个应用程序的不同组件中注入依赖关系,而不知道这些依赖关系是如何创建的,也不知道它们本身需要哪些其他依赖关系。
我们定义了getArticles() 方法,它从服务器返回一个可观察的文章列表。
addArticles() 函数使用POST 方法向我们的远程服务器添加一篇文章。
创建自动完成组件
在本节中,我们将通过运行以下命令来创建一个Angular自动完成组件。
ng g c autocomplete
接下来,在autocomplete.component.html 文件中添加以下模板。
<h3>List of articles on Section</h3>
<mat-form-field>
<input type="text" placeholder="start typing..." matInput [formControl]="name"
[matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let article of articles" [value]="article">
{{article}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
在上面的字段中,我们有一个输入字段,用户在这里输入文章的标题。这个字段有Angular材料attributes 和ReactiveForms 值。
然后我们定义mat-autocomplete ,这是我们在本教程中感兴趣的元素。
<mat-option></mat-option> 有一个ngFor 指令,用来循环浏览文章列表,当用户开始输入时,这些文章就会被推荐。
现在我们已经准备好了过滤文章的模板,让我们继续实现从服务器上检索列表的逻辑。
//app.component.ts
import { Component, OnInit } from '@angular/core';
import { FormControl,ReactiveForms } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { debounceTime, tap, switchMap, finalize, distinctUntilChanged, filter } from 'rxjs/operators';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
searchArticlesCtrl = new FormControl();
filteredArticles: Article;
selectedArticle:Article;
constructor(
private apiService: ApiService
) { }
ngOnInit() {
this.autocomplete();
}
//autocomplete
autocomplete(){
this.searchArticlesCtrl.valueChanges
.pipe(
filter(res => {
return res !== null && res.length >= this.minLengthTerm
}),
distinctUntilChanged(),
debounceTime(2000),
tap(() => {
this.filteredArticles = [];
}),
switchMap(value => this.apiService.getArticles()
.pipe(
finalize(() => {
this.loading = false
}),
)
)
)
.subscribe((res: Article) => {
if (data['Search'] == undefined) {
this.errorMsg = res['Error'];
this.filteredArticles = [];
} else {
this.filteredArticles = res['Search'];
}
});
}
// selecting article
onSelectingArticle() {
this.selectedArticle = this.selectedArticle;
}
// display article with
displayArticleWith(value: Article) {
return value?.Title;
}
// clear article
clearArticleSelection() {
this.selectedArticle = "";
this.filteredArticles = [];
}
在上面的代码中,我们首先导入我们的API服务。
然后,我们定义了autocomplete() 函数,我们用它来进行API请求,以检索文章的列表。
接下来,我们使用内置的方法,根据数值的变化来过滤文章。
运行你的应用程序
我们可以使用以下命令来运行该应用程序。
ng serve --port 4200
上述命令将启动我们的网络服务器,端口为4200 。
你可以通过在你的浏览器上导航到localhost:4200 来访问该应用程序。为了测试它,试着在输入栏中随机输入文章标题。
注意,远程服务器没有运行。要测试这个应用程序,你将需要一个能够返回文章列表的活动服务器。
总结
在本教程中,我们讨论了如何使用Angular material来构建一个向用户推荐文章标题的应用。
mat-autocomplete 功能允许我们根据来自远程服务器的数据自动推荐文章。