Is there a way to extract data from a single line?

In my code, I have a simple object retrieved like this:

  getSelectedRecipients(event) {
    this.aliasesService.getRecipients(event.nr)
    .subscribe(
      res => {
        this.recipients = res;
        this.isVisible = true;
      },
      err => console.error(err)
    );
  }

The output of

this.recipients
is:

{
recipients:
"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="741b1a1134101b19151d1a5a171b19">[email protected]</a>,↵
<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a5d1d2cae5c1cac8c4cccb8bc6cac8">[email protected]</a>,↵
<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="50243822353510343f3d31393e7e333f3d">[email protected]</a>,↵
<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cea8a1bbbc8eaaa1a3afa7a0e0ada1a3">[email protected]</a>
"}

I now need to display this data in a table. Currently, it looks like this:

<td id="recipients">
{{recipients.recipients }}
</td>

Resulting in:

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="deb1b0bb9ebab1b3bfb7b0f0bdb1b3">[email protected]</a>, <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="760201193612191b171f185815191b">[email protected]</a> ... <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="63050c161123070c0e020a0d4d000c0e">[email protected]</a> [button]

However, I want the displayed format to be:

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="acc3c2c9ecc8c3c1cdc5c282cfc3c1">[email protected]</a> [button]
<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4430332b04202b29252d2a6a272b29">[email protected]</a> [button]
.
.
.
<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8cec7dddae8ccc7c5c9c1c686cbc7c5">[email protected]</a> [button]

How can I achieve this formatting? I need it for the next step which involves allowing the user to delete a specific recipient, such as [email protected], instead of all recipients at once.

Answer №1

To begin, my recommendation is to construct a pipe that will divide the recipients:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'split-recipients'})
export class SplitRecipientsPipe implements PipeTransform {
  transform(recipients: string[]) {
    return recipients
        .split(',')
        .filter(Boolean)
        .map(r => r.trim());
  }
}

If you prefer each recipient to be displayed in its own table row (<tr>):

<tr *ngFor="let r of recipients.recipients | split-recipients">
  <td>{{r}}</td>
  <td style="width: 60px"><button (click)="_delete(r, recipients)">REMOVE</button></td>
</tr>

If you want all recipients to be kept within the same <td> element:

<td id="recipients">
  <div style="display:flex;justify-content:space-between;width:100%;" 
       *ngFor="let r of recipients.recipients | split-recipients">
    <span>{{r}}</span>
    <button (click)="_delete(r, recipients)">REMOVE</button>
  </div>
</td>

Regarding the _delete method, written in the ts file:

/**
 * It's important to note that recipients refers to the object containing 
 *   the list of recipient strings, not the string itself.
 */
_delete(emailToDelete: string, recipients: any) {
  const newRecipients = recipients.recipients
        .split(',')
        .filter(Boolean)
        .map(r => r.trim())
        .filter(r => r !== emailToDelete)
        .join(',');

  recipients.recipients = newRecipients;
}

Answer №2

#recipients {
   white-space: pre-line;
}

Essentially, this inquiry mirrors the one found at Angular 4 display in next line for newline character for p tag

Answer №3

To split your recipients.recipients, you can use the .split() method by specifying the delimiter as ,. After splitting, you can utilize Angular's ngFor attribute to iterate through and render the array.

const recipientsArray = recipients.recipients.split(',')

<td *ngFor="let recipient of recipientsArray">
{{recipient }}
</td>

Answer №4

Utilize the split("\n") method to separate the string by a newline, then implement a ngFor loop.

class A {
  getSelectedRecipients(event) {
    this.aliasesService.getRecipients(event.nr).subscribe(
      (res) => {
        this.recipients = res.recipients.split("\n");
        this.isVisible = true;
      },
      (err) => console.error(err)
    );
  }
}
<td id="recipients" *ngFor="let recipient of recipients">
{{recipient}}
</td>

Revise the example for the logic:

const recipients = [
  "user1",
  "user2",
  "user3",
  "user4",
]
let deletedUsers = []
const deleteUser = (user) => deletedUsers.push(user)

const listUsers = () => {
  return recipients.filter(user => deletedUsers.indexOf(user) === -1)
}
console.log(listUsers()) // [ 'user1', 'user2', 'user3', 'user4' ]
deleteUser("user2")
console.log(listUsers()) // [ 'user1', 'user3', 'user4' ]

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

The navigation bar options are not collapsing as intended

When I resize my page to width:750px;, my navigation bar is not collapsing the items. Despite trying to edit my CSS, I am still clueless. Here is my live page. This is the CSS for my slidebar: @media (max-width: 480px) { /* Slidebar width on extra small ...

Unable to execute the 'getElementsByTagName' function as null value is passed as the parameter

I'm encountering a problem with my first AJAX attempt and my first time using a .php file. I'm working through an exercise in the text, but things aren't going as expected. To troubleshoot, I've been using the alert function extensively ...

Issue with displaying entire object using Jest and console.dir

I'm having trouble displaying an error in my Jest test because it's not showing all the levels as expected. import util from 'util' describe('Module', () => { it('should display all levels WITHOUT util', () =& ...

Using Directives inside a Standalone Component in Angular: A Step-by-Step Guide

As I work on integrating a directive that is not standalone into a Standalone component, I encountered an error. The specific error message can be viewed here. Even after including the directive in the component's import array as shown here, the issu ...

Take away the dropdown selection once the form has been submitted

Every day, a user fills out a form ten times. They choose an option from the dropdown menu, fill out the form, and submit it. I am looking for a solution to either remove the selected option once it's been submitted or mark it as complete by highlight ...

The background size does not adjust to the size of the viewport

I am encountering an issue with the background size on my webpage. When changing the viewport size on this page , the background does not adjust to the new viewport dimensions immediately. It seems to retain the previous dimension and only updates to the c ...

Creating an overlay with CSS hover on a separate element and the ::before pseudo class

Issue: I am struggling to display the overlay when hovering over the circle element, rather than just the image itself. I have attempted to achieve this using CSS, but can't seem to make it work as intended. Any guidance and examples using JavaScript ...

Launching a program through a web browser - a step-by-step guide

I am looking to create a specific sequence of events: A web browser opens, and a user logs in (the exact action is not crucial) The user is then redirected to a new page where another program should automatically open This process is similar to what happ ...

Shine a spotlight on elements that match with jQuery using live() or on()

Check out my jsFiddle demonstration where I have created a button that adds elements and provides links to delete these elements. Instead of actually deleting the elements in this example, I want to make it so that hovering over the (remove) link, which is ...

What is the best way to refresh the slick jQuery plugin for sliders and carousels?

I am currently facing an issue with two buttons that have the same function. The purpose of these buttons is to retrieve data from an API, convert it to HTML, and then append it to a <div> using jQuery. Finally, the data is displayed using the slick ...

Updating the light and OrbitControls in three.js

I am currently utilizing threejs to showcase an object and using OrbitControls to manage the movement of the scene with my mouse. Additionally, my scene features a DirectionalLight. Initially, when the scene is rendered, the DirectionalLight illuminates m ...

Receiving a JSON object in response after sending data to a server using JavaScript

I am facing an issue with passing an email and password on login click to a database using PHP. After testing the email and password combination, PHP sends back a JSON object. While I have verified that the PHP code is functioning correctly and returns a J ...

Violation of content security policy due to the usage of inline styling in the tawk.to

I have incorporated Tawk.to's chat widget codes into my website to include the chat bubble. The code is placed within a JS file: var Tawk_API = Tawk_API || {}, Tawk_LoadStart = new Date(); (function() { var s1 = document.createElement("script&qu ...

What is the best way to stop a jQuery function from applying titles extracted from the first row th's in thead's to multiple tables in a document?

My circumstances: I am new to jQuery and Stack Overflow, seeking assistance for my website project. The challenge: Building a website using Bootstrap 3.3.6 with intricate data tables that need to be stacked dynamically on mobile devices using CSS. It is c ...

Using React hooks to reset state in a reducer: step-by-step guide

event.js import React, { useEffect, useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { Link, useHistory } from 'react-router-dom'; import { addEvent } from '../actions/event'; ...

Send a React component to another component as a prop

I am looking to pass the entire parent component as props to its child component. However, when attempting to pass data from parent to child, I ended up importing the child into the parent. Is there another way to achieve this? Any suggestions on how I c ...

JavaScript not correctly evaluating the if condition

I'm facing an issue with a section of my code where a variable is supposed to contain a specific string (in this case, it's multiply), but when I try to check if the variable actually holds that string, it always returns false. I've scrutini ...

Trouble with Bootstrap Collapse feature not collapsing on its own

I recently added a Bootstrap collapse feature to my payment view in Laravel. The Bootstrap section collapses when clicked, but I would like it to be collapsed by default. I understand that I need to include: aria-expanded="false" However, it still doesn& ...

Retrieve the jQuery widget instance by selecting an element within the widget

I am currently developing a widget using the Jquery widget factory. The abbreviated version of the code looks something like this: _create: function(){ this.element.hide(); //hides original input element this.newInput=$("<input>"); //creates ...

Using Laravel Blade Variables in JavaScript Code

Trying to access a variable within blade syntax has posed a challenge for me: success: function(resp) { console.log(resp) var MsgClass = 'alert-danger'; $("#overlay").hide(); ...