如何使用angular8中的反应形式来选择和取消选择复选框

时间:2020-01-15 14:05:41

标签: javascript angular

嗨,我有一个具有id和value的对象数组,我使用反应形式绑定到html,当我单击select并取消全选时,我没有得到任何错误,也没有得到所需的输出。我不知道问题出在哪里。

HTML:

<div class="col">

    <div class="row row-cols-3" formGroupName="Print">
        <div class="col" *ngFor="let print of PrintList;let i = index">
            <div class="custom-control custom-checkbox mb-3">
                <input type="checkbox" class="custom-control-input" id="{{print .id}}">
                <label class="custom-control-label" for="{{print.id}}">{{print.value}}</label>
            </div>
        </div>
        <div class="col">
            <div class="custom-control custom-checkbox mb-3">
                <input type="checkbox" class="custom-control-input" id="SelectDeselectAll" [checked]="isAllChecked()"
                    (change)="checkAll($event)">
                <label class="custom-control-label" for="SelectDeselectAll">Select/Deselect All</label>
            </div>
        </div>
    </div>
</div>

Ts:

checkAll(ev) {
    this.PrintList.forEach(x => x.id = ev.target.checked)
}

isAllChecked() {
    return this.PrintList && this.PrintList.every(_ => _.id);
}

PrintList = [{ id: 1, value: "flowers" }, { id: 2, value: "fruits" }, { id: 1, value: "cars" }, { id: 1, value: "bikes" },]

Demo

1 个答案:

答案 0 :(得分:0)

尝试这样做:

HTML:

<div class="col">

<div class="row row-cols-3" >
    <div class="col" *ngFor="let print of PrintList;let i = index">
        <div class="custom-control custom-checkbox mb-3">
            <input type="checkbox" class="custom-control-input" id="{{print .id}}" [checked]="print.checked">
            <label class="custom-control-label" for="{{print.id}}">{{print.value}}</label>
        </div>
    </div>
    <div class="col">
        <div class="custom-control custom-checkbox mb-3">
            <input type="checkbox" class="custom-control-input" id="SelectDeselectAll" [checked]="all"
                (change)="checkAll($event)">
            <label class="custom-control-label" for="SelectDeselectAll">Select/Deselect All</label>
        </div>
    </div>
</div>

TS:

all = false;

checkAll(ev) {
if (!this.all) {
    this.PrintList.forEach(x => x.checked =  true)
    this.isAllChecked()
    } else {
    this.PrintList.forEach(x => x.checked =  false)
    this.isAllChecked()
 }
 }

 isAllChecked() {
   this.all = !this.all
 }

 PrintList = [
   { id: 1, checked: false, value: "flowers" },
   { id: 2, checked: false, value: "fruits" },
   { id: 1, checked: false, value: "cars" },
   { id: 1, checked: false, value: "bikes" },
  ]
 }

DEMO