我有一個包含專案的陣列,并用它填充了一個 ngFor,它用我的復選框向我顯示了我的專案串列,我需要進行驗證,以使這些專案中至少有一個是強制性的。
一個例子是=如果一個復選框被選中而另一個未被選中,我不能取消選中已選中的復選框,我需要只禁用已選中的復選框,我只能取消選中它,如果我選中我的復選框未選中,因此它被啟用等等。
我試過這個
<div *ngFor="let item of dataList"\>
<input type="checkbox" [checked\]="item.checked" (change)="itemSelected($event, item)" [disabled]="notSelectCheck">
itemSelected(value, level ) {
level.checked = value.target.checked
const valuesChecked = this.dataList.filter((dt) =\> dt.checked).length;
valuesChecked \< 2 ? (this.notSelectCheck = true) : (this.notSelectCheck = false)
}
uj5u.com熱心網友回復:
這將始終選中最后一個復選框,并允許您根據需要檢查任意數量的復選框。您只需要計算已檢查元素的數量并使用 preventDefault() 如果總檢查==1:
<div *ngFor="let element of elements; let i = index">
<input
name="elem{{ i }}"
id="elem{{ i }}"
[(ngModel)]="element.checked"
type="checkbox"
[checked]="element.checked"
(click)="checkElement($event, i)"
/>
<label for="elem{{ i }}">{{ element.text }}</label>
</div>
.ts
elements: any = [
{
checked: true,
text: 'Element 1',
},
{
checked: true,
text: 'Element 2',
},
{
checked: true,
text: 'Element 3',
},
{
checked: false,
text: 'Element 4',
},
];
checkElement(e: any, index: number) {
//checks if the user is checking or unchecking a checkbox
if (!e.target.checked) {
//if the user unchecked a checkbox, then I count the number of checked checkboxes
let totalChecked = 0;
for (let checked of this.elements) {
if (checked.checked) {
totalChecked = totalChecked 1;
}
}
//if the number of checked checkboxes is 1, then I cancel the uncheck action with e.preventDefault(), and reassign true to the unchecked value.
if (totalChecked == 1) {
e.preventDefault();
this.elements[index].checked = true;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/447485.html
上一篇:我的AngularWeb應用程式按預期通過按鈕進行路由,但是當我在url中鍵入頁面路徑時,路由不起作用。在Firebase上托管時
