【问题标题】:How to only only allow ONE item to be selected at a time如何一次只允许选择一项
【发布时间】:2018-10-25 19:36:51
【问题描述】:

Angular 5 - 当一个节点处于活动状态时(点击),所有其他节点都需要处于非活动状态。选定的节点将变为绿色(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;

}

【问题讨论】:

  • 如果您点击一个活动节点,您只会进入 isActive=false 部分。看起来像一个切换功能。最简单的方法是将所有节点设置为 isActive = false (没有条件)。最后让 node.isActive = true 的部分;
  • 谢谢!是的,它目前是一个切换功能。当前,所有节点都设置为 isActive=false,直到它们被单击,这将激活 isActive 切换。当单击一个节点时,我希望所有其他节点都处于非活动状态.. 仍然不确定如何实现这一点.. 抱歉,对编程来说相当新。

标签: html typescript angular5


【解决方案1】:

我建议走 @Edub 在 cmets 中建议的路线,那就是:

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;
}

【讨论】:

  • 谢谢亚历克斯!我的 html 是一样的,我已经用你的建议替换了我的函数。我在此处的节点下收到错误“shadowed name 'node' no shadowed variable”---> this.data.map(node =>
  • 啊对,那是因为方法参数和箭头函数是一样的,我给你修改代码。
猜你喜欢
  • 1970-01-01
  • 2017-12-08
  • 2014-10-17
  • 1970-01-01
  • 1970-01-01
  • 2012-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多