在Angular 8中,可以使用Mat-Chip来显示和处理一个或多个小的信息片段,如标签、关键词或小图标。以下是一个示例,展示了如何使用Mat-Chip来设置chip数据的值。
首先,确保已经安装了Angular Material库和Mat-Chips模块。在app.module.ts文件中导入MatChipsModule:
import { MatChipsModule } from '@angular/material/chips';
@NgModule({
imports: [
// other imports
MatChipsModule
],
// other code
})
export class AppModule { }
然后,在你的组件模板中,使用MatChipList和MatChip来显示和处理chip数据的值。在这个示例中,我们将一个数组的值绑定到MatChipList上,并使用*ngFor循环来遍历数组并显示每个值:
{{ chip }}
在组件类中,定义一个名为chips的数组,并添加一些示例值:
export class AppComponent {
chips: string[] = ['Tag 1', 'Tag 2', 'Tag 3'];
}
这样,当组件被加载时,MatChipList会根据数组中的值自动创建相应的MatChip。
你还可以通过添加事件处理程序来处理chip的选择和删除。例如,添加一个方法来处理chip的删除事件:
{{ chip }}
cancel
在组件类中,添加一个removeChip方法来处理chip的删除事件:
export class AppComponent {
chips: string[] = ['Tag 1', 'Tag 2', 'Tag 3'];
removeChip(chip: string): void {
const index = this.chips.indexOf(chip);
if (index >= 0) {
this.chips.splice(index, 1);
}
}
}
这样,当用户点击chip的删除图标时,removeChip方法会被调用,并从数组中删除相应的chip。
这就是一个使用Angular 8和Mat-Chip的示例,展示了如何设置chip数据的值并处理chip的选择和删除。你可以根据自己的需求进行修改和扩展。