如何只允许一次选择一个项目

时间:2018-05-15 21:07:03

标签: html typescript angular5

Angular 5 - on(单击)当一个节点处于活动状态时,所有其他节点都需要处于非活动状态。所选节点将变为绿色(在CSS中有效 - ' - [ngClass]),所有未选择当前节点的节点应变为黑色。

这是我的HTML和打字稿 HTML:

 <div class="row">
    <div class="col-xs-10 col-sm-10 col-md-8" (contextmenu)="onRightClick($event, node)">
      <div class="toggle" [ngClass]="{'active': node.isActive}" (click)="activeButton(node)">
        <div [ngStyle]="node.styles()">
            <i *ngIf="node.getChildren().length > 0 && !node.isExpanded()"
               (click)="node.toggle()">
              <i class="fa fa-plus"></i>
            </i>
            <i *ngIf="node.getChildren().length > 0 && node.isExpanded()"
               (click)="node.toggle()">
              <i class="fa fa-minus"></i>
            </i>
            <i *ngIf="node.getChildren().length === 0">
              <i class="fa fa-circle-notch"></i>
            </i>
              {{node.title}}

打字稿:

activeButton(node) {
if (node.isActive) {
  const index = this.data.indexOf(node);
  console.log(this.data.indexOf(node));
  if (this.data.indexOf(node) !== -1) {
    this.data[index] = node;
    console.log(this.data.indexOf(node));
    node.isActive = false;
  }
}
node.isActive = true;

}

1 个答案:

答案 0 :(得分:1)

我建议去@Edub在评论中建议的路线,这样就可以了:

activeButton(currentNode): void {
  this.data = this.data.map(node => {
    node.isActive = false;
    return node;
  });

  // or this.data.forEach(node => node.isActive = false);

  if (currentNode.isActive) {
    const index = this.data.indexOf(currentNode);

    if (this.data.indexOf(currentNode) !== -1) {
      currentNode.isActive = false;
      this.data[index] = currentNode;
    }
  }

  currentNode.isActive = true;
}