Как использовать ngFor для аккордеона несколько раз в Angular - PullRequest
0 голосов
/ 01 июля 2018

У меня есть следующий код для создания аккордеона с использованием значков плюс и минус. Я также обработал функцию переключения. Но теперь я хочу зациклить это внутри ngFor для нескольких наборов элементов. Я не уверен, как это сделать. В основном у меня есть resultArray, который является JSON. Мне нужно перебрать resultArray json, чтобы получить заголовок и описание, и поместить его как заголовок аккордеона и описание аккордеона. Я не уверен, как динамически заменить accord.id.

HTML

<div *ngFor = "let resulArray of resultArray">
     <div *ngFor="let accord of accordian;">
                  <div (click)="toggle(accord.id)" id="accordionTitle{{accord.id}}" class="accordionTitle active">{{accord.label}}
                    <i class="fa fa-minus" id="minus{{accord.id}}"></i>
                  </div>
                  <div id="{{accord.id}}" *ngIf="accord.id == 0" class="hidden-data show">
</div>
</div> 

Переключатель ниже - применить стили и изменить значки с плюса на минус для аккордеона. Когда вызывается функция переключения

ц.

this.accordian = [{
      id: 0, label: 'Accordion title'
    }];

toggle(id) {
    this.x = document.getElementById(id);
    this.y = document.getElementById('accordionTitle' + id);
    if (this.x.className.indexOf('show') === -1) {
      this.x.className += ' show';
      this.y.className += ' active';
      document.getElementById('minus' + id).classList.remove('fa-plus');
      document.getElementById('minus' + id).classList.add('fa-minus');
    } else {
      /*  this.x.className = this.x.className.replace('hide', ''); */
      this.x.className = ' hide';
      /*   this.y.className = this.y.className.replace('', ''); */
      this.y.className = 'accordionTitle';
      document.getElementById('minus' + id).classList.remove('fa-minus');
      document.getElementById('minus' + id).classList.add('fa-plus');
    }
}

1011 * JSON * resultArray = { 'status': 'SUCCESS', 'responseCode': '000', 'errorMessage': null, 'cboRequestList': [ { 'seqNo': 1, 'applicableFor': '0', 'applicableForText': 'Hide', 'displayDesc': null, 'displaySeqNo': 1, 'description': 'ABCDisplayDesc1', 'type': 'W', 'content': null, 'field1': null, 'field2': null, 'field3': null, 'field4': null, 'markerId': null, 'markerLastModifiedTime': null, 'countryCode': null, 'languageCode': null, 'commentMaker': null }, { 'seqNo': 2, 'applicableFor': '0', 'applicableForText': 'Hide', 'displayDesc': null, 'displaySeqNo': 1, 'description': 'ABCDisplayDesc1', 'type': 'W', 'content': null, 'field1': null, 'field2': null, 'field3': null, 'field4': null, 'markerId': null, 'markerLastModifiedTime': null, 'countryCode': null, 'languageCode': null, 'commentMaker': null } ], }

Ответы [ 2 ]

0 голосов
/ 01 июля 2018

Вы используете [ngClass] неправильно.

Сначала вы должны объявить имя класса, а затем оценить значение true или false для вашей переменной.

пример:

<i class="fa " [ngClass]="{'fa-plus': someBoolean1, 'fa-minus': someBoolean2 }" aria-hidden="true"></i>

Это выражение означает, что fa-plus будет применяться, когда someBoolean1 будет true и fa-minus будет применяться, когда someBoolean2 будет true

Вы можете применять столько классов, сколько захотите, с помощью ngClass.

В вашем случае вы должны обрабатывать истинные или ложные оценки в соответствии с toggle [i] следующим образом:

<i class="fa " [ngClass]="{'fa-plus': toggle[i], 'fa-minus': !toggle[i]}" aria-hidden="true"></i>

Относительно того, как применять стили: Используя [ngStyle] = "{'color': exp}" для каждого необходимого элемента. Обратите внимание, что «exp» означает выражение, которое должно быть переменной или функцией для оценки имени цвета или кода.

Пример:

exp = 'green';
<h1 [ngStyle]="{'color': exp }">My Text</h1>
0 голосов
/ 01 июля 2018
 <div class="row justify-content-md-center bussinessOffice">
  <div class="col-md-9 bussiness">
      <h3 class="mainTitile">Help</h3>
      <p class="bottom-30">
          How may i help you today ?
      </p>
<div *ngFor="let resultArrayText of cboRequestListArray; let i = index">
      <ul class="list-group bottom-30" (click)="toggle[i] = !toggle[i]">
          <li class="list-group-item"  ng-class="{'activateToggle': toggle[i], '': !toggle[i]}" >
              {{resultArrayText.description}}
              <i class="fa" [ngClass]="toggle[i] ? 'fa-plus': 'fa-minus'" aria-hidden="true"></i>
          </li>
          <div *ngIf="!toggle[i]" class="container activateToggle">
            <p class="content-30">
              Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
              Lorem Ipsum has been the industry's standard dummy text ever since the 
              1500s
            </p>
              <p>
                <strong>Refer for more informations:</strong> <a>Click View Documents</a>
              </p>
              </div>
            </ul>
</div>


        </div> 
        </div>
...