Html 隐藏按钮隐藏所有按钮而不是一个

Html hide button is hiding all buttons instead of one

我试图在单击时隐藏按钮。

component.ts:

import { Component, Input, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { DataService } from '../../shared/service/data.service';
import { TreeNode } from '../../shared/dto/TreeNode';

import html from './rightside.component.html';
import css from './rightside.component.css';

@Component({
  selector: 'rightside-component',
  template: html,
  providers: [DataService],
  styles: [css],
  changeDetection: ChangeDetectionStrategy.OnPush
})

export class RightSideComponent implements OnInit {
  selections: string[];
  @Input() treeNode: TreeNode<string>[];
  hide: boolean = false;

  constructor(private cd: ChangeDetectorRef) {}

  ngOnInit() {
  }

  getSelections() : TreeNode<string>[] {
    if (typeof(this.treeNode) == "undefined" || (this.treeNode) === null) {
      return [];
    }
    return this.treeNode;
  }

  deselect(item: TreeNode<string>): void {
    this.hide = true;
    if((item.children) !== null) {
      item.children.forEach(element => {
        this.deselect(element);
      });
    }
    item.selected = false;
  }

}

component.html:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<div>
  <ul class="selection-list">
    <li *ngFor="let item of getSelections()">
      <button class="btn" (click)="deselect(item)" *ngIf="!hide">
        <i class="fa fa-close"> {{ item.displayName }} </i>
      </button> 
    </li>
  </ul>
</div>

当我点击任何按钮时,所有项目都消失了。我只想让点击的项目消失。当我再次 select 复选框时,该项目应该重新出现。我想实现类似于我发现的这个 plunkr 的东西,但对于我的数据结构:

http://next.plnkr.co/edit/1Fr83XHkY0bWd9IzOwuT?p=preview&utm_source=legacy&utm_medium=worker&utm_campaign=next&preview

我该如何解决这个问题?让我知道是否需要任何其他代码。

试试这个

  hide= [];

    <div>
      <ul class="selection-list">
        <li *ngFor="let item of getSelections();let i=index">
          <button class="btn" (click)="deselect(item: 
           TreeNode<string>);hide[i]=!hide[i]" *ngIf="hide[i]">
            <i class="fa fa-close"> {{ item.displayName }} </i>
          </button> 
        </li>
      </ul>
    </div>

不要使用通用的 hide 变量,而是在每个项目中使用 selected 属性,因为当您取消选择时,它会变成 false。

<button class="btn" (click)="deselect(item)" *ngIf="item.selected">
   <i class="fa fa-close"> {{ item.displayName }} </i>
</button> 

您的所有项目都会消失,因为它们都共享相同的 "hide" 属性,因此当您单击其中一个时,所有项目都会发生变化。您应该拥有的是每个项目的属性(此属性应初始化为 true)

component.html

<div>
  <ul class="selection-list">
    <li *ngFor="let item of getSelections()">
      <button class="btn" (click)="deselect(item)" *ngIf="item.selected">
        <i class="fa fa-close"> {{ item.displayName }} </i>
      </button> 
    </li>
  </ul>
</div>

component.ts

    deselect(item: TreeNode<string>): void {
        item.selected = false;
        if((item.children) !== null) {          
            item.children.forEach(element => {
            this.deselect(element);
          });
        }
    }