使用Angular2将所有复选框更改为true或false

时间:2018-08-28 11:07:34

标签: angular

我正在尝试将所有复选框更改为true或false,并在HTML中更改为1复选框,但在console.log()中得到了更改;我得到默认值

我正在使用Ngmodel,但我认为我对此失败。

COMPONENT.TS

public checkall: boolean = false;
public closures: Array<item>;

HTML->

<div class="toggle-switch">
    <input type="checkbox" id="checkAll" name="checkAll" (change)="check()" [(ngModel)]="checkall">
 <label for="checkAll"></label>
</div>

<tr *ngFor="let closure of closures">

<input type="checkbox" id="{{closure.id}}"  (change) = "check()" name = "{{closure.id}}"[(ngModel)] = "closure.checkclosure"[checked] = "checkall" >
<label for="{{closure.id}}"></label>



check() {
    console.log(this.closures);
}

output-> false,但是在我的html中,我的复选框为true。

3 个答案:

答案 0 :(得分:2)

这有效:

.ts:

  closures = [
    { "id": 1, "checkclosure": false },
    { "id": 2, "checkclosure": false },
    { "id": 3, "checkclosure": false },
    { "id": 4, "checkclosure": false },
    { "id": 5, "checkclosure": false }
  ]

  public checkall: boolean = false;

  check() {
    console.log(this.closures);
  }

  checkAllFunc() {
    this.closures.forEach(elem => {
      elem.checkclosure = this.checkall
    })
  }

.html:

<div class="toggle-switch">
  <input
    type="checkbox"
    id="checkAll"
    name="checkAll"
    (change)="checkAllFunc()"
    [(ngModel)]="checkall">
   <label for="checkAll"></label>
</div>

<hr/>

<div *ngFor="let closure of closures">
  <input
    type="checkbox"
    id="{{closure.id}}"
    (change)="check()"
    name="{{closure.id}}"
    [(ngModel)]="closure.checkclosure">
  <label for="{{closure.id}}"></label>
  {{closure.checkclosure}}
</div>

Check Demo here

答案 1 :(得分:0)

您可以使用以下代码对其进行修复

  

TS

checkall: boolean = false;
  closures =  [{ "id":1,"checkclosure":false},{ "id":2,"checkclosure":false},{ "id":3,"checkclosure":false},{ "id":4,"checkclosure":false},{ "id":5,"checkclosure":false}]

  check() {
    for(var i in this.closures){ //loop through to update your value of checkbox
      this.closures[i].checkclosure = this.checkall
    }
    console.log(this.closures);
  }
  

HTML

<div class="toggle-switch">
    <input type="checkbox" id="checkAll" name="checkAll" (change)="checkAll()" [(ngModel)]="checkall">
 <label for="checkAll"></label>
</div>

<tr *ngFor="let closure of closures">

<input type="checkbox" id="{{closure.id}}"  name = "{{closure.id}}"[(ngModel)] = "closure.checkclosure">
<label for="{{closure.id}}"></label>

答案 2 :(得分:0)

您的checkall值仅从组件流到模板,而没有绑定到closure.checkclosure的值,因为它们恰好位于同一元素上。即除非您以编程方式单击元素/,否则closure.checkclosure不会得到更新。

我会选择:

check(event) {
  this.closures = this.closures.map(closure => {
    return {...closure, checkclosure: this.checkall};
  });
}

我将像这样更改模板:

<div *ngFor="let closure of closures">
  <input type="checkbox" id="{{closure.id}}" name="{{closure.id}}" [(ngModel)]="closure.checkclosure">
  <label for="{{closure.id}}"></label>
</div>