Delve deeper or skim the surface, caught within the confines of angular

Is there a way to prevent the class for each notification from changing when I click on something? I want to create a read more/read less functionality in Angular for notifications, and have all notifications expand when the button is clicked.

<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>",
    }
];

I am using this dummy data for testing, as I will be receiving similar data from the server.

I am new to development, so please bear with me. I have used the method below and it seems to work fine. Is this the best practice?

<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>

Answer №1

Utilizing a single central variable for toggling the show/hide functionality would impact all instances where it is used.

To customize the state of each object individually, you need to introduce an additional property in every object within the altersList array.

Controller (*.ts)

// After initializing `alertsList` 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 using mock data from a service, you can still utilize the same Array#map method to add an extra property to each object. Simply skip the subscribe section for now.

Component

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn how to properly implement cookies in a fetch request within Nextjs

Here is a code snippet to consider: Index.getInitialProps = async function({req}) { const res = await fetch("http://localhost/api/tiles"); const json = await res.json(); } If the /api/tiles endpoint requires access to the uid cookie from the user, t ...

Checkmarking Options for Multiple Selection in P-Tables [PrimeNG]

I am struggling with implementing "Multiple selection (click + shift)" on checkboxes and cannot figure out how to make it work. The documentation provides an example called "Checkbox Selection" with a note that says, "Multiple selection can also be handle ...

It seems like encodeURIComponent is appending an extra character to my string

jQuery.ajax() is behaving strangely when escaping my data. For instance, if I make the following request: $.ajax({ url: 'somethingordinary', data: { name: 'Ihave¬aweirdcharacter'; } }); upon inspecting the XHR in ...

Navigate back to the previous URL and remove any search parameters using React-router-dom V6

After navigating to a page with certain search parameters, I needed to go back to the previous URL and clear the search params. To achieve this, I utilized the useSearchParams function provided by react-router-dom v6. Within the useEffect hook, I implemen ...

Creating and inserting multiple objects into a table in Sails JS while bypassing any existing rows

Is there a way to insert an array of objects into a table while avoiding duplicate rows? I have a model defined as follows: //Test.js module.exports={ tableName:'test', connection: 'mysqlServer', attributes:{ id:{ type: ...

The issue of basic authentication failing to function on Internet Explorer and Chrome, yet operating successfully on Firefox

Here is how my authentication code looks: public class BasicAuthenticationMessageHandler : DelegatingHandler { private const string BasicAuthResponseHeader = "WWW-Authenticate"; private const string BasicAuthResponseHeaderValue = "Basi ...

What are some ways to make autorun compatible with runInAction in mobx?

Currently delving into the world of mobx and runInAction, facing a challenge in comprehending why autorun fails to trigger my callback in this particular scenario: class ExampleClass { // constructor() { // this.exampleMethod(); // } ...

What's the best way to retrieve the dates for the current week using JavaScript?

Could anyone help me find a way to retrieve the first and last dates of the current week? For example, for this week, it would be from September 4th to September 10th. I encountered an issue at the end of the month when dates overlap two months (such as t ...

I'm having trouble getting the JADE tag to render in Express script. Can anyone help me

I am trying to include client-side script in my JADE template and so far I have: extends layout script. function collect_data() { var transitions = {}; $( ":checkbox:checked" ).each(function (index, element) { //// some code ...

Initiating Angular APP_INITIALIZERThe Angular APP_INITIALIZER

I am a newcomer to Angular and currently utilizing Angular6 for development purposes. I have a specific query regarding my app. Before the app initializes, I need to invoke three services that provide configurations required by the app. Let's refer to ...

Executing a Prisma query with a selection

My Prisma models involve User, Car, and Reservation entities: model User { id String @id @default(auto()) @map("_id") @db.ObjectId name String? email String? @unique emailVerified DateTime? image ...

What is the best way to retrieve the API response with a status code of 400?

When I consume an API, I handle different status codes differently. If the API returns a 200 status code, I return the response. However, if the API returns a 400 status code, it returns an array with errors. My question is, how do I access and return this ...

Issue with cross-origin security when applying HTML5 video tag to a webGL texture

I am trying to link a remote video to a texture in WebGL. To allow the video source to be different from the document source, I added Access-Control-Allow-Origin:* to the http headers of the video source. Additionally, I set an anonymous origin for the vid ...

Discover a revolutionary Android app that provides detailed indoor maps and step-by-step walking directions

I am looking to enhance a custom Google map by adding sidewalks for walking, while keeping all of its original features intact. Additionally, I want to create a detailed interior map of a building on a college campus, complete with classroom locations on ...

What is the best way to extract and retrieve the most recent data from an XmlHttpRequest?

Currently, I am using a web service that returns an SseEmitter to program a loading bar. The method to receive it looks like this: static async synchronize(component: Vue) { let xhr = new XMLHttpRequest(); xhr.open('PATCH', 'myUrl.co ...

The table is too wide for its parent mat-nav-list, stretching to 100%

Here is the code snippet I am using to display a table inside a mat-nav-list: <mat-nav-list> <table> <tr>Node Information</tr> <tr> <td>Name</td> <td *ngIf="activeNod ...

Adjust the contents of an HTTP POST request body (post parameter) upon activation of the specified POST request

Is there a way to intercept and modify an HTTP Post Request using jQuery or JavaScript before sending it? If so, how can this be achieved? Thank you. ...

Guide: "Adding markers to user-uploaded images - A step-by-step tutorial"

I'm struggling to create a website that allows users to upload images and use specific tools. However, I am facing an issue where the marker I want to add is appearing all over the webpage instead of just on the image itself. How can I confine it to o ...

Creating mathematical formulas in JavaScript

How can the equation be translated into JavaScript? This is the proposed programming solution, but there seems to be an issue. var MIR = parseFloat(($('#aprrate').val() / 100) / 12); var paymentAmount = (MIR * $('#amounttofinance').va ...

Is there a way to modify the image of a single face in a Cubemap using THREE.js?

In my project, I am attempting to showcase a panorama using cubemaps by initially loading and displaying 6 low-quality images on the cubemap. Achieving this can be easily done through the following code: var urls = [ 'path/to/low-q-pos-x.png', & ...