我正在使用PrimeNG 14 (和角14)。我有一个输入产品信息的表单,我希望将产品与一个或多个类别相关联,每个类别都显示为复选框。
<form [formGroup]="form" (ngSubmit)="submit()">
...
<p-table #dt [value]="(categories$ | async)!"
[(selection)]="selectedCategories"
dataKey="categoryId">
<ng-template pTemplate="header">
<tr>
<th>
<p-tableHeaderCheckbox></p-tableHeaderCheckbox>
</th>
<th pSortableColumn="name">
<div>
Category
<p-sortIcon field="name"></p-sortIcon>
<p-columnFilter type="text" field="name" display="menu"></p-columnFilter>
</div>
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-category>
<tr class="p-selectable-row">
<td>
<p-tableCheckbox [value]="category" [formControl]="$any(form.controls['categoryIds'])"></p-tableCheckbox>
</td>
<td>
<span class="p-column-title">Category</span>
{{category.name}}
</td>
</tr>
</ng-template>
</p-table>
在我的服务班里
form!: FormGroup;
...
ngOnInit(): void {
...
this.form = this.fb.group({
...
categoryIds: []
});
问题是,我不知道如何将类别ID复选框绑定到窗体控件。使用上述方法不起作用,因为当我选中一个复选框时,它们都会被选中。
发布于 2022-12-03 06:33:24
若要将复选框绑定到窗体控件,可以对每个复选框元素使用formControlName属性。下面是如何更新代码:
<form [formGroup]="form" (ngSubmit)="submit()">
...
<p-table #dt [value]="(categories$ | async)!"
[(selection)]="selectedCategories"
dataKey="categoryId">
<ng-template pTemplate="header">
<tr>
<th>
<p-tableHeaderCheckbox></p-tableHeaderCheckbox>
</th>
<th pSortableColumn="name">
<div>
Category
<p-sortIcon field="name"></p-sortIcon>
<p-columnFilter type="text" field="name" display="menu"></p-columnFilter>
</div>
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-category>
<tr class="p-selectable-row">
<td>
<input type="checkbox" formControlName="categoryIds" [value]="category.categoryId">
</td>
<td>
<span class="p-column-title">Category</span>
{{category.name}}
</td>
</tr>
</ng-template>
</p-table>
</form>
注意,在上面的代码中,我们使用formControlName属性将每个复选框绑定到表单组中的categoryIds控件,并使用value属性指定复选框的值。
当表单提交时,您可以使用categoryIds控件的value属性访问所选的类别is,例如。
发布于 2022-12-03 18:20:17
您可以在formArrayName
元素上使用p-tableCheckbox
属性,并提供表单数组控件的名称作为值。
<form [formGroup]="form" (ngSubmit)="submit()">
...
<p-table #dt [value]="(categories$ | async)!"
[(selection)]="selectedCategories"
dataKey="categoryId">
<ng-template pTemplate="header">
<tr>
<th>
<p-tableHeaderCheckbox></p-tableHeaderCheckbox>
</th>
<th pSortableColumn="name">
<div>
Category
<p-sortIcon field="name"></p-sortIcon>
<p-columnFilter type="text" field="name" display="menu"></p-columnFilter>
</div>
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-category>
<tr class="p-selectable-row">
<td>
<p-tableCheckbox [value]="category" formArrayName="categoryIds"></p-tableCheckbox>
</td>
<td>
<span class="p-column-title">Category</span>
{{category.name}}
</td>
</tr>
</ng-template>
</p-table>
在服务类中,您可以创建一个名称为FormArray
的categoryIds
控件,并将其添加到表单组中:
ngOnInit(): void {
...
this.form = this.fb.group({
...
categoryIds: this.fb.array([])
});
}
这将允许将每个复选框绑定到categoryIds
窗体数组控件中的相应元素,并允许您将选定的类别in作为表单数据的一部分提交。
https://stackoverflow.com/questions/74631454
复制相似问题