How to show only one ul at a time in angular using

2019-08-29 19:50发布

问题:

I have the above image which has Add Person button, on click of Add person, Person 1 row gets created and so on. On the right end of each row, I have a share icon, on click of an icon, I wanted to open a ul element. The problem is the number of popups that gets displayed depends on the number of rows. If 5 rows are added, then 5 popups are displayed. Ideally, I need only one popup to be displayed, for Person 4 row it should be the popup with 33( basically the popup the is present for that particular row). I tried to add *ngIf = i> 1 condition, but the popup with 00 is only displayed every time which is not correct because the popup position will always be in parallel to Person 1 position.

<div>
    <div *ngFor="let person of persons; let i = index">
      <div>
        <div class="userIcon">
          <div>
            <img class="person-img" src="assets/images/person.png" alt="My Profile">
          </div>
          <div>
            <input id="form3" class="form-control" type="text">
            <label for="form3" class="">{{person.name}}</label>
          </div>
        </div>
      </div>
      <div>
        <div>
          <input id="form5" class="form-control" #enteramount type="text">

          <a class='dropdown-trigger sharebtn' href='#' data-target='dropdown{{i}}' (click)="shareIconClicked($event, i,  enteramount)"></a>
            {{i}}
          <ul id='dropdown{{i}}'  [ngClass]="{'popupShare': showPopup == true}" class='dropdown-content sharebtn-content'>
            <li>  {{i}}
             Copy Message
            </li>

            <li>Whatsapp</li>

            <li>Email</li>

          </ul>
        </div>
      </div>

    </div>
  </div>

Below image represents the single popup after adding ngIf = 'isFirst'. I have clicked the Person 4 share icon. If I click the Person 3 share or Person 5 share icon, the popup is always positioned on the first row.

回答1:

Just add check for first using *ngFor like this -

<div *ngFor="let person of persons; first as isFirst">
....
            <ul id='dropdown{{i}}' *ngIf='first'  [ngClass]="{'popupShare': showPopup == true}" class='dropdown-content sharebtn-content'>
...</ul>
</div>

For more in details refer official docs -

  • https://angular.io/api/common/NgForOf


回答2:

You should try angular Mat-menu feature like this.

<div *ngFor="let person of persons; first as isFirst">
   .... code

  <button mat-button [matMenuTriggerFor]="menu">Share</button>
   <mat-menu #menu="matMenu">
    <button mat-menu-item (click)="sharteWithFacebook(person)">Facebook</button>
    <button mat-menu-item (click)="shareWithWhatapp(person)">Whatsapp</button>
   </mat-menu>
</div>