【发布时间】:2019-09-23 04:16:50
【问题描述】:
我正在尝试使用 Ng 形式添加 Angular 材料的芯片列表列表。我无法单击按钮添加新的芯片列表,也不知道如何显示新芯片列表中添加的数组值。这是一个例子 https://stackblitz.com/edit/angular-4d5vfj-g1ggqr
<button (click)="addNewChip()">Add new Chip</button><br><br>
<form [formGroup]="myForm">
<mat-form-field class="example-chip-list">
<mat-chip-list #chipList formArrayName="names">
<mat-chip
*ngFor="let name of myForm.get('names').controls; let i=index;"
[selectable]="selectable"
[removable]="removable"
(removed)="remove(myForm, i)">
{{name.value}}
<mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
</mat-chip>
<input placeholder="Names"
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event, myForm)">
</mat-chip-list>
<mat-error>Atleast 1 name need to be added</mat-error>
</mat-form-field>
</form>
component.ts 文件
export class ChipListValidationExample implements OnInit {
@ViewChild('chipList') chipList: MatChipList;
public myForm: FormGroup;
// name chips
visible = true;
selectable = true;
removable = true;
addOnBlur = true;
readonly separatorKeysCodes: number[] = [ENTER, COMMA];
// data
data = {
names: ['name1', 'name2']
}
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
names: this.fb.array(this.data.names, this.validateArrayNotEmpty)
});
}
ngOnInit() {
this.myForm.get('names').statusChanges.subscribe(
status => this.chipList.errorState = status === 'INVALID'
);
}
initName(name: string): FormControl {
return this.fb.control(name);
}
validateArrayNotEmpty(c: FormControl) {
if (c.value && c.value.length === 0) {
return {
validateArrayNotEmpty: { valid: false }
};
}
return null;
}
add(event: MatChipInputEvent, form: FormGroup): void {
const input = event.input;
const value = event.value;
// Add name
if ((value || '').trim()) {
const control = <FormArray>form.get('names');
control.push(this.initName(value.trim()));
console.log(control);
}
// Reset the input value
if (input) {
input.value = '';
}
}
remove(form, index) {
console.log(form);
form.get('names').removeAt(index);
}
addNewChip(){
console.log("Yse")
this.myForm = this.fb.group({
names: this.fb.array(this.data.names, this.validateArrayNotEmpty)
});
}
}
【问题讨论】:
-
您正在尝试将芯片添加到芯片列表或将芯片列表添加到现有表单??
-
您需要使用 controlValueAccessor 来定义一个接口,该接口充当 Angular 表单 API 和 DOM 中的本机元素之间的桥梁。 angular.io/api/forms/ControlValueAccessor
-
尝试以现有形式添加芯片列表。单击添加按钮时,每次都应该显示一个输入表单,我可以在其中添加筹码..
-
@Subham 请检查发布的答案
标签: angular typescript angular-material