CliffC
CliffC

Reputation: 933

ngFor hide unhide details

I have the following json array

    users= [
      {'name':'cliff'
       'age':'44'
       'bloodtype':'A'
       'hobby':'Golf'
      },
      {'name':'andy'
       'age':'30'
       'bloodtype':'b'
       'hobby':'running'
      }]

and i have the following code which will loop through all users and display its details

<div *ngFor='let user of users >
    <div>Name:{{user.name}}</div>
    <div>Age:{{user.age}}</div>
    <div>BloodType:{{user.bloodtype}}</div>
    <div>Hobby:{{user.hobby}}</div>
    <a href="#">More</a>
</div>

What i want to do is to hide 'bloodtype', 'hobby' field on initial load for all users and unhide individual user details when the 'More' link is clicked. How can i accomplish this?

I have tried the following but clicking 'More' link will unhide all users details

<div *ngFor='let user of users >
    <div>Name:{{user.name}}</div>
    <div>Age:{{user.age}}</div>
    <div [hidden]=isHidden>
      <div>BloodType:{{user.bloodtype}}</div>
      <div>Hobby:{{user.hobby}}</div>
    <div>
    <a href="#" (click)='isHidden=!isHidden'>More</a>
</div>

Upvotes: 0

Views: 173

Answers (3)

ranakrunal9
ranakrunal9

Reputation: 13558

Try with below ngFor :

<div *ngFor="let user of users" >
    <div>Name:{{user.name}}</div>
    <div>Age:{{user.age}}</div>
    <div *ngIf="user.isMore">
        <div>BloodType:{{user.bloodtype}}</div>
        <div>Hobby:{{user.hobby}}</div>
    </div>
    <a *ngIf="!user.isMore" (click)="user.isMore = !user.isMore">More</a>
</div>

Upvotes: 1

Maximilian Riegler
Maximilian Riegler

Reputation: 23506

Have a seperate array which holds the current state:

additionalInfo: Array<boolean> = [ false, false ];
users: Array<any> = [
  {'name':'cliff'
   'age':'44'
   'bloodtype':'A'
   'hobby':'Golf'
  },
  {'name':'andy'
   'age':'30'
   'bloodtype':'b'
   'hobby':'running'
  }]

And modify your HTML template like this. Add the index variable in your *ngFor and then add the *ngIf on the divs and the anchor and also a (click) event to toggle the state.

<div *ngFor="let user of users; let i=index" >
    <div>Name:{{user.name}}</div>
    <div>Age:{{user.age}}</div>
    <div *ngIf="additionalInfo[i]">BloodType:{{user.bloodtype}}</div>
    <div *ngIf="additionalInfo[i]">Hobby:{{user.hobby}}</div>
    <a *ngIf="!additionalInfo[i]" (click)="additionalInfo[i] = true">More</a>
</div>

Upvotes: 2

Roman Skydan
Roman Skydan

Reputation: 5748

Use *ngIf Implement click function, that return current person. And then yo can do this. In this div you can add your field, that you want hide

<div *ngIf="currentPerson">  
  //your info
</div> 

You can find full answer and exemple here

Upvotes: 0

Related Questions