为什么将手风琴放在ngFor内后会停止工作

时间:2019-06-05 12:33:41

标签: angular

尝试使此手风琴在组件模板中工作,使其在ngFor外部时起作用,但在其内部时不展开

<div *ngFor="let article of articles;">
            <button class="accordion">Section 1</button>
            <div class="panel">
              <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
            </div>
          </div>

当它在ng外面时它可以工作暂时将其放在里面,因为手风琴无法打开,所以它停止工作。 Btw ngFor在我的情况下有效,它重复了该部分。

ngAfterViewInit() {
    var acc = document.getElementsByClassName("accordion");
    var i;

    for (i = 0; i < acc.length; i++) {
      acc[i].addEventListener("click", function() {
        this.classList.toggle("activee");
        var panel = this.nextElementSibling;
        if (panel.style.maxHeight){
          panel.style.maxHeight = null;
        } else {
          panel.style.maxHeight = panel.scrollHeight + "px";
        } 
      });
    }
  }

css

/* Accor */
.accordion {
    background-color: #eee;
    color: #444;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
    transition: 0.4s;
  }

  .activee, .accordion:hover {
    background-color: #ccc;
  }

  .accordion:after {
    content: '\002B';
    color: #777;
    font-weight: bold;
    float: right;
    margin-left: 5px;
  }

  .activee:after {
    content: "\2212";
  }

  .panel {
    padding: 0 18px;
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
  }

1 个答案:

答案 0 :(得分:0)

更好的方法是将每篇文章的状态保持为

articles: any[] = [  //it could have other properties like article text etc.
    { id: 1, visible: true },
    { id: 2, visible: true },
    { id: 3, visible: true },
    { id: 4, visible: true },
    { id: 5, visible: true }
];

并将状态切换为

(click)="article.visible = !article.visible"

您可以使用它来控制元素的存在

*ngIf="article.visible"

或将条件类绑定用作

[class.visible]="article.visible"

https://stackblitz.com/edit/angular-ysmaxp

上存在的工作示例