通过在angular2中选中/取消选中,从数组中不断添加和删除元素

时间:2016-12-09 16:53:05

标签: html5 angular typescript

我在angular2遇到了问题,我有4个复选框(md-checkbox),它们是: enter image description here

这是他们的HTML

<div class="show-orders">
  <md-checkbox [checked]="true" (click)="showOpenOrders(isOpen)">
    <span class="show-orders-label">{{'open' | translate}}</span>
  </md-checkbox>
  &nbsp;&nbsp;&nbsp;
  <md-checkbox [checked]="true" (click)="showInProgOrders(isInProg)">
    <span class="show-orders-label">{{'in_progress' | translate}}</span>
  </md-checkbox>
  &nbsp;&nbsp;&nbsp;
  <md-checkbox (click)="showCompletedOrders(isCompleted)">{{completedStatus}}
    <span class="show-orders-label">{{'completed' | translate}}</span>
  </md-checkbox>
  &nbsp;&nbsp;&nbsp;
  <md-checkbox (click)="showCancelledOrders(isCancelled)">
    <span class="show-orders-label">{{'cancelled' | translate}}</span>
  </md-checkbox>
</div>

这是他们在TS文件中的简单函数实现

showOpenOrders(isOpen: boolean) {
    if (isOpen) {
    console.log('open');
    }
    this.isOpen = !isOpen;
  }

  showInProgOrders(isInProg: boolean) {
    if (isInProg) {
      console.log('in prog');
    }
    this.isInProg = !isInProg;
  }

  showCompletedOrders(isCompleted: boolean) {
    if (!isCompleted) {
      console.log('completed');
    }
    this.isCompleted = !isCompleted;
  }

  showCancelledOrders(isCancelled: boolean) {
    if (!isCancelled) {
      console.log('cancelled');
    }
    this.isCancelled = !isCancelled;
  }

如您所见,我有两个默认选中的复选框, 我想要的是我有一个默认的array字符串:

  

status: string[ ]= ['open','in_progress','','']

我希望每个复选框上的每个click,一个字符串将不断添加到数组中或从中删除,具体取决于checkbox的状态是否已选中< / strong>或,我没有要求完整的解决方案,TypeScript和HTML5的一些指导就足够了,谢谢你提前..

1 个答案:

答案 0 :(得分:0)

在您调用console.log的同一个地方,您可以调用一个从列表中添加或删除字符串的函数,例如:

private addOption(option){
   this.status.push(option);
}

private removeOption(option){
   this.status = this.status.filter(_option => _options != option)
}

在您的点击功能中,您可以执行以下操作:

showInProgOrders(isInProg: boolean) {
    if (isInProg) {
        ...
        this.addOption('in_progress');
    } else {
        this.removeOption('in_progress');
    }
    ...
}