Warm tip: This article is reproduced from serverfault.com, please click

Ngfor to array and access via ngif

发布于 2020-11-28 07:39:55

I am trying to have basically a read more on a post that is created using Angular NgFor loop. I have my data printing out just fine, but I have tried a bunch of different things to get NgFor to push to an array or something so that one I click on a post to show more data it doesn't open all of the posts on the page. Right now, if I click on one post to show more, all the posts on the page expand to show more content.

Here is a snip of my code that is running the NgFor loop and the NgIf. Any suggestions on how to push to an array?

<tr *ngFor="let policy of needs; let i = index">
      <div *ngIf="!this.isInfoVisible">
      <a href="" class="listing-link"  (click)="this.isInfoVisible = true">
      <table class="needs-posting">
      {{i}}

I tried to do something like this, but was only getting errors:

<tr *ngFor="let policy of needs; let i = index; addPost()">
      <div *ngIf="this.isInfoVisible[{{i}}] = false">
      <a href="" class="listing-link"  (click)="this.isInfoVisible[{{i}}] = true">
      <table class="needs-posting">
      {{i}}

with

addPost()
{
     this.isInfoVisible.push(false);
}

I don't know if I am onto the correct concept, but just with wrong syntax or something. First time using Angular here. Thanks!

Questioner
Connor Thomas
Viewed
0
Owen Kelvin 2020-11-28 23:39:35

In your code you are binding to isInfoVisible that is in the code <div *ngIf="!this.isInfoVisible"> this indicates that the value will display when isInfoVisible is true. When of isInfoVisible turns to true all the contents display because each of the contents is bound to this.

Try below approach. In your TS file

  isInfoVisible: boolean[] = [false]

In your html

<tr *ngFor="let policy of needs; let i = index">
      <div *ngIf="!this.isInfoVisible[i]">
      <a href="" class="listing-link"  (click)="this.isInfoVisible[i] = true">
      <table class="needs-posting">
      {{i}}

With the above, each item will be bound to a specific index in the property isInfoVisible