首先,确保你已经安装了Angular和Angular Material。
然后,创建一个新的组件,例如chip-list.component.ts
,并将以下代码添加到该文件中:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-chip-list',
templateUrl: './chip-list.component.html',
styleUrls: ['./chip-list.component.css']
})
export class ChipListComponent {
chipForm: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.chipForm = this.formBuilder.group({
chips: [[]]
});
}
addChip(chipValue: string): void {
const chips = this.chipForm.get('chips') as FormControl;
chips.setValue([...chips.value, chipValue]);
}
removeChip(chipValue: string): void {
const chips = this.chipForm.get('chips') as FormControl;
const chipIndex = chips.value.indexOf(chipValue);
if (chipIndex >= 0) {
chips.value.splice(chipIndex, 1);
chips.updateValueAndValidity();
}
}
}
然后,创建一个新的模板文件,例如chip-list.component.html
,并将以下代码添加到该文件中:
最后,确保在需要使用该组件的模块中导入并声明MatInputModule
和ReactiveFormsModule
:
import { NgModule } from '@angular/core';
import { MatInputModule } from '@angular/material/input';
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
MatInputModule,
ReactiveFormsModule
],
declarations: [ChipListComponent]
})
export class YourModule { }
现在,你就可以在其他组件中使用
来显示带有formGroup
的材料芯片列表了。