搜索在角度中不起作用的可折叠内容



我已经在我的角度应用程序中实现了可折叠。但是这些可折叠的内容来自数据库服务,我正在ngFor的帮助下设置这些可折叠内容-

 <input type="text" name="search" class="form-control" id="myInput" onkeyup="myFAQsSearchFun()" placeholder="Enter your query " >

 <div *ngFor="let item of faqs;let i = index;" id="div2">
     <button class="accordion" (click)="toggleAccordian($event, i)">
         <a style="text-decoration:none;" > {{item.question}}</a> 
     </button>
     <div class="panel"  hide="!item.isActive">
         <p><br> {{item.answer}} </p>
     </div>
     <br>
 </div>

可折叠工作正常,但问题是我想根据我在搜索栏中输入的内容搜索这些内容。为此,我实现了以下代码-

  function myFAQsSearchFun() {
                var input, filter, ul, li, a, i, txtValue;
                input = document.getElementById("myInput");
                filter = input.value.toUpperCase();
                ul = document.getElementById("div2");
                li = ul.getElementsByTagName("button");
                window.alert(li.length);
                for (i = 0; i < li.length; i++) {
                    a = li[i].getElementsByTagName("a")[0];
                    txtValue = a.textContent || a.innerText;
                    if (txtValue.toUpperCase().indexOf(filter) > -1) {
                        li[i].style.display = "";
                    } else {
                        li[i].style.display = "none";
                    }
                }
            }

Window.alert 给出的输出为 "1"。但是 ngFor 循环了 3 次,因为我可以看到 3 个可折叠对象。

我做错了什么。请帮忙。

提前感谢!

  • 不要使用 document.getElementById("myInput"(,而是使用 Angular 表单来获取输入。
  • 您将在控制器中提供以 HTML 形式显示的数据,因此您无需循环访问 DOM,只需在控制器本身中过滤数组即可。
  • 过滤后,只需为常见问题解答中的每个项目添加一个标志即可隐藏或显示它们。
  • 根据上述标志在 HTML 中添加 ngIF。

.HTML:

<input [(ngModel)]="model.search" >
<div *ngFor="let item of faqs;let i = index;" >
  <div *ngIf="!item.hidden">
     <button class="accordion" (click)="toggleAccordian($event, i)">
        <a style="text-decoration:none;" > {{item.question}}</a> 
     </button>
     <div class="panel"  hide="!item.isActive">
        <p><br> {{item.answer}} </p>
     </div>
     <br>
   </div>
 </div>

.JS:

       model = {search: ''};
       faqs = [{question:'asf',answer:'asd'}, {question:'asf',answer:'asd'}]
       myFAQsSearchFun() {
            var input, filter, ul, li, a, i, txtValue;
            input = model.search;
            filter = input.toUpperCase();
            faqs.forEach((faq) => {
               if (faq.question.toUpperCase().indexOf(filter) > -1) {
                  faq.hidden = false;
               } else {
                  faq.hidden = true;
               }
            });
        }

最新更新