在表单中发送 mat-chip-list,您可以按照以下步骤进行操作:
<form [formGroup]="myForm">
<mat-form-field>
<mat-chip-list formControlName="chips">
<mat-chip *ngFor="let chip of myForm.get('chips').value" [removable]="true" (removed)="removeChip(chip)">
{{ chip }}
<mat-icon matChipRemove>cancel</mat-icon>
</mat-chip>
</mat-chip-list>
<input type="text" placeholder="Add chip" [matChipInputFor]="chipList" [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="true" (matChipInputTokenEnd)="addChip($event)">
</mat-form-field>
</form>
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements OnInit {
myForm: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.myForm = this.formBuilder.group({
chips: new FormControl([])
});
}
addChip(event: any): void {
const input = event.input;
const value = event.value;
if ((value || '').trim()) {
const chips = this.myForm.get('chips').value;
chips.push(value.trim());
this.myForm.get('chips').setValue(chips);
}
if (input) {
input.value = '';
}
}
removeChip(chip: string): void {
const chips = this.myForm.get('chips').value;
const index = chips.indexOf(chip);
if (index >= 0) {
chips.splice(index, 1);
this.myForm.get('chips').setValue(chips);
}
}
}
这样,您就可以在表单中发送 mat-chip-list 了。用户可以通过输入框添加新的 chip,并且可以通过点击 chip 上的取消按钮来移除已选择的 chip。
请注意,以上代码示例中使用的是 Angular Material 的 mat-chip-list 组件,如果您使用的是其他 UI 框架或库,可能会有不同的实现方式。
领取专属 10元无门槛券
手把手带您无忧上云