Read more Read less stuck in angular

Viewed 211

How do I make sure that the class for each notification does not change when I press the ..., I want to implement read more read less in angular for given notifications, and with this, if I press the button all the notifications get opened.

<div class="notificationList" *ngFor="let a of alertsList">
    <div [ngClass]="{'showLess': more}" [innerHTML]="a.Message"></div>
    <a class="readMore" (click)="more==!more">...</a>
</div>
public alertsList: any = [
    {
        "Message": "<p>hi hello</p><p>dsaddddsdad ad s sdaf asf sf sd sd fsa ff sdf af s fsa f sadf sa faf sadf a a fa</p>",
    },

    {
        "Message": "<p>hi hello</p><p>dsaddadsaddd ad s sdaf asf sf sd sd fsa ff sdf af s fsa f sadf sa faf sadf a a fa</p>",
    },

    {
        "Message": "<p>hi hello</p><p>dsadddd ad gfgdgfds sdaf asf sf sd sd fsa ff sdf af s fsa f sadf sa faf sadf a a fa</p>",
    },

    {
        "Message": "<p>hi hello</p><p>dsadddd ad s sdadfgfdgf asf sf sd sd fsa ff sdf af s fsa f sadf sa faf sadf a a fa</p>",
    }
];

Using this dummy data to check, as I will be receiving data from the server in this manner only

I am a new developer so please bare with me, i used this method below and it worked can you please tell me if its the best practice or not?

<div class="notificationList" *ngFor="let a of alertsList; index as i">
    <div [ngClass]="{'showMore': more[i], 'showLess': !more[i]}" [innerHTML]=" a.Message">
    </div>
    <a class="readMore" (click)="more[i]=!more[i]">...</a>
</div>
1 Answers

If you use a single central variable to control the show/hide feature, then it'd naturally affect all the places it's used in.

You have to introduce an additional property in each object of the altersList array to individually adjust each object's state.

Controller (*.ts)

// assuming `alertsList` is initialized in a subscription

this.someService.getAlerts().pipe(
  map((alerts: any) =>
    alerts.map(alert => ({ ...alert, more: true }))
  )
).subscribe((alerts: any) => 
  this.alertsList = alerts
);

Template (*.html)

<div  class="notificationList" *ngFor="let a of alertsList">
  <div [ngClass]="{'showLess': a.more}" [innerHTML]="a.Message" ></div>
  <a class="readMore" (click)="a.more=!a.more">...</a>
</div>

Update

If you're using mock data from a service, you could still use the same Array#map function to include an additional property to the object. Just ignore the subscribe part for now.

Component

this.alertsList = this.someService.alertsList.map(
  alerts.map(alert => ({ ...alert, more: true }))
);
Related