ОБНОВЛЕНИЕ
Попробуйте это:
import { Component } from "@angular/core";
import { list } from './list';
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
list: Array<any>;
checked = [];
shouldCheckboxesBeDisabled = false;
ngOnInit() {
this.list = list;
this.recheckDisablingStatus();
}
recheckDisablingStatus() {
this.shouldCheckboxesBeDisabled = this.list.filter(item => item.checked).length >= 5;
}
uncheckIfAlreadyChecked(itemIndex) {
const isChecked = this.list[itemIndex].checked;
this.list[itemIndex].checked = isChecked ? false : isChecked;
this.recheckDisablingStatus();
}
}
И в шаблоне:
<table border="1">
<thead>
<td>ID</td>
<td>Name</td>
<td>Checked</td>
<td>Uncheck if Already Checked</td>
</thead>
<tbody>
<tr *ngFor="let item of list; let i = index">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>
<input
[disabled]="shouldCheckboxesBeDisabled && !list[i].checked"
type="checkbox"
[(ngModel)]="list[i].checked"
(change)="recheckDisablingStatus()">
</td>
<td><button (click)="uncheckIfAlreadyChecked(i)">Uncheck If Checked</button></td>
</tr>
</tbody>
</table>
Вот это Рабочий образец StackBlitz для вашей ссылки.
ОРИГИНАЛЬНЫЙ ОТВЕТ
Дайте эту попытку:
<table border="1">
<thead>
<td>ID</td>
<td>Name</td>
<td>Checked</td>
</thead>
<tbody>
<tr *ngFor="let item of list$ | async; let i = index">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>
<input
[disabled]="shouldCheckboxesBeDisabled && checked.indexOf(item.id) < 0"
type="checkbox"
(change)="onCheckBoxChange(item.id, $event.target.checked)">
</td>
</tr>
</tbody>
</table>
И в вашем компоненте:
import { Component } from "@angular/core";
import { Observable, of } from "rxjs";
import { HttpClient } from "@angular/common/http";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
list$: Observable<Array<any>>;
checked = [];
shouldCheckboxesBeDisabled = false;
constructor(private http: HttpClient) {}
ngOnInit() {
// this.list$ = this.http.get<Array<any>>('/assets/data.json');
this.list$ = of([
{
id: 1,
name: "Name 1",
checked: false
},
{
id: 2,
name: "Name 2",
checked: true
},
{
id: 3,
name: "Name 3",
checked: false
},
{
id: 4,
name: "Name 4",
checked: true
},
{
id: 5,
name: "Name 5",
checked: false
},
{
id: 6,
name: "Name 6",
checked: true
},
{
id: 7,
name: "Name 7",
checked: false
},
{
id: 8,
name: "Name 8",
checked: true
},
{
id: 9,
name: "Name 9",
checked: false
},
{
id: 10,
name: "Name 10",
checked: true
}
]);
}
onCheckBoxChange(itemId, checked) {
if(checked) {
this.checked.push(itemId);
} else {
const itemIndexToRemove = this.checked.indexOf(itemId);
this.checked.splice(itemIndexToRemove, 1);
}
this.shouldCheckboxesBeDisabled = this.checked.length >= 5;
}
}
Вот вам Рабочий образец StackBlitz для вашей ссылки.