至少可以说这是“非常规的”,但问题是您的名称控件实际上需要存在于表单数组之外,因为它不属于数组中的每个项:
<form action="" [formGroup]="myForm">
<mat-form-field class="example-chip-list">
<mat-chip-list #chipList>
<ng-container formArrayName="arr"> <!-- array here -->
<mat-chip *ngFor="let a of arr.controls; let i = index"
[selectable]="selectable"
[removable]="removable"
(removed)="remove(a)"
[formGroupName]="i"> <!-- ngFor and group here -->
{{a.get('text').value}} <!-- show text control value -->
<mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
<mat-radio-group aria-label="Select an option" formControlName="code">
<mat-radio-button value="1">1</mat-radio-button>
<mat-radio-button value="2">2</mat-radio-button>
</mat-radio-group>
</mat-chip>
</ng-container>
<input formControlName="name"
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event)">
</mat-chip-list>
</mat-form-field>
</form>
然后修改组件:
constructor(private _fb: FormBuilder) {
this.myForm = this._fb.group({
name: [''], // add name control here
arr: this._fb.array([]) // init empty
})
}
createItem(text) { // change this to have text ctrl and accept value
return this._fb.group({
text: [text], // set value
code: [null] // optional to add default val here
})
}
get arr() { // handy helper
return this.myForm.get('arr') as FormArray;
}
add(event: MatChipInputEvent): void {
const value = event.value;
if ((value || '').trim()) {
this.arr.push(this.createItem(value)); // feed in the value
}
// Reset the input value for the reactive form
this.myForm.get('name').setValue('');
}
下面是您的remove函数的外观:
remove(i: index) {
this.arr.removeAt(i);
}
在模板中,使用索引调用它:
(removed)="remove(i)"