如何在Angular 9应用程序中实现 “添加标签 “功能
Angular使得实现几乎所有的功能变得非常容易。在这篇文章中,我们将学习如何在你的Angular应用程序中实现添加标签功能。添加标签在多个领域都有应用,如音乐应用、在线购物应用等。通过使用这个功能,我们可以根据用户的需要来过滤搜索结果。
步骤:
- Angular材料库提供了mat-chip,它可以用来实现这个功能。
- 我们可以在一个表单字段内使用它来接受用户的输入并更新我们的标签列表。
- 一旦用户完成了添加标签,我们就可以保存标签列表。
- 现在我们有了我们的标签列表,我们可以以任何我们想要的方式使用它。
分步实现:
对于组件类。
- 从@angular/material/chips导入MatChipInputEvent,以处理标签输入事件。
- 从@angular/cdk/keycodes中导入COMMA , ENTER,以增加分隔键。
- 创建一个列表,其中将包含用户输入的所有标签。
- 创建你的自定义添加和删除方法来添加和删除标签。
- 该组件的代码。
import {Component} from '@angular/core';
import {COMMA, ENTER} from '@angular/cdk/keycodes';
import {MatChipInputEvent} from '@angular/material/chips';
@Component({
selector: 'add-tags',
templateUrl: 'tags.html',
styleUrls: ['tags.css'],
})
export class addTags {
/*Set the values of these properties
to use them in the HTML view.*/
visible = true;
selectable = true;
removable = true;
/*set the separator keys.*/
readonly separatorKeysCodes: number[] = [ENTER, COMMA];
/*create the tags list.*/
Tags: string[] = [];
/*our custom add method which will take
matChipInputTokenEnd event as input.*/
add(event: MatChipInputEvent): void {
/*we will store the input and value in local variables.*/
const input = event.input;
const value = event.value;
if ((value || '').trim()) {
/*the input string will be pushed to the tag list.*/
this.Tags.push(value);
}
if (input) {
/*after storing the input we will clear the input field.*/
input.value = '';
}
}
/*custom method to remove a tag.*/
remove(tag: string): void {
const index = this.Tags.indexOf(tag);
if (index >= 0)
{
/*the tag of a particular index is removed from the tag list.*/
this.Tags.splice(index, 1);
}
}
}
对于HTML视图。
- 创建一个表单字段,它将接受输入并显示标签列表。
- 有一些参数。
matChipInputFor:它接收表单字段的ID,我们将从中获取标签的输入。
- matChipInputSeparatorKeyCodes。它获取将被用作分隔符的键的值。
- matChipInputTokenEnd:一旦用户按下分离键,这将包含最后输入的标签,我们可以通过我们的自定义添加方法更新标签列表。
- 要删除一个特定的标签,可以用matChipRemove指令添加一个mat-icon。
- HTML视图的代码。
<!DOCTYPE html>
<html>
<head>
<title>tutorial</title>
</head>
<body>
<mat-form-field class="input">
<!--this contains the list of tags-->
<mat-chip-list #taglist>
<!--set the properties for the tags-->
<mat-chip selected color="primary"
*ngFor="let Tag of Tags"
[selectable]="selectable"
[removable]="removable"
(removed)="remove(Tag)">
{{Tag}}
<!--add icon with matChipRemove
directive to remove any tag-->
<mat-icon matChipRemove
*ngIf="removable">cancel
</mat-icon>
</mat-chip>
<input placeholder="Add Tags"
[matChipInputFor]="taglist"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
(matChipInputTokenEnd)="add($event)" />
</mat-chip-list>
</mat-form-field>
</body>
</html>
- 现在在主组件中包括这个’add-tags’组件。
import {Component} from '@angular/core';
@Component({
selector: 'app-root',
template: `
<div style="align-items: center;">
<app-test></app-test>
</div>
`,
styleUrls: ['main.css'],
})
export class AppComponent {
}
- 我们已经成功实现了添加标签功能。
输出:表格字段上的Mat-chips代表用户输入的标签。

极客教程