Save the ID values of selected users in Angular Mentions feature

Using the angular mentions library, I successfully incorporated a textarea that enables me to mention multiple users.

Is there a method to store the IDs of the selected users? Ideally, I would like to save them as an array of strings.

For instance: If I choose users Name 1, Name 2, Name 3 .... I desire to save their IDs rather than names. ["1", "2", "3"]

Could someone lend me a hand with this?

Thank you!

Stackblitz

HTML

 <div [mention]="items" class="form-control" contenteditable="true" style="border:1px lightgrey solid;min-height:88px" [mentionConfig]="{triggerChar:'@',labelKey:'name'}"></div>

Component.ts

 items: string[];
  constructor(private userService: UserService) {}

  ngOnInit() {
    this.userService.getUsers().subscribe(
      (val: any[]) =>{
        this.items = val;
      } 
    )
  }

Answer №1

1- Start by using a textarea instead of a div element in order to utilize [(ngModel)] for binding the selected user names.

<textarea type="text" [mention]="items" 
 class="form-control" contenteditable="true" style="border:1px lightgrey solid;min-height:88px" [mentionConfig]="{triggerChar:'@',maxItems:10,labelKey:'name'}" [(ngModel)]="data"></textarea>

2- Create a variable called 'data' to bind all the text input from the textarea.

3- Utilize the JSON data to create TypeScript classes that represent the JSON properties, making data filtering easier.

export interface Geo {
  lat: string;
  lng: string;
}

... (additional TypeScript interfaces)

export interface RootObject {
  id: number;
  name: string;
  username: string;
  email: string;
  address: Address;
  phone: string;
  website: string;
  company: Company;
}

4- Implement the 'save' method to retrieve all the selected name IDs.

 save() {
        let ids = this.data.replace(/(\r\n|\n|\r)/gm, "").split("@").filter(t => t != "" && this.items.findIndex(u => u.name == t.trim()) > -1).map(name => this.items.find(s => s.name == name.trim()).id);
  }

Check out the demo here

Answer №2

I highly recommend utilizing the library fvi-angular-mentions. With fvi-angular-mentions, you have the ability to retrieve the selected users.

The current library lacks an eventEmitter to capture the selected username. It is limited to only 3 event emitters:

@Output() searchTerm EventEmitter<string>-This event is triggered whenever the search term changes, allowing for asynchronous search functionality.
@Output() opened EventEmitter<void>-Triggered when the mentions panel is opened.
@Output() closed EventEmitter<void>-Triggered when the mentions panel is closed.

Unfortunately, these options do not meet your requirements.

Answer №3

It appears that the Mention module functions by binding exclusively to a string value - hence, you will need to implement the following modifications using the map operator:

.ts

this.userService.getUsers().subscribe((val: any[]) => {
   // converting each value to a string
   this.items = val.map((e: any) => String(e.id));
});

.html

<div 
   [mention]="items" class="form-control" 
   contenteditable="true" 
   style="border:1px lightgrey solid;min-height:88px" 
   [mentionConfig]="{triggerChar:'@',labelKey:'id'}">  // update made here
</div>

Check out a demo for reference.

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

Issue: ReactJS - $npm_package_version variable not functioning properly in build versionIn the current

After trying this suggested solution, unfortunately, it did not work for my specific case. The React application I am working on was initialized with CRA version 5.0.1 and currently has a version of 18.2.0. Additionally, the dotenv version being used is 1 ...

Using Lerna with Docker for Next.js and GraphQL applications

Currently, I am working with lerna and everything runs smoothly locally. However, when I attempt to build the image and operate it through Docker, it does not function as expected. FROM node:16-alpine3.11 ENV NODE_ENV=production COPY . /app WORKDIR /app R ...

Establish a permanent code folding feature in the Monaco editor for enhanced text organization

I need help implementing persistent code folding on the Monaco editor. Specifically, I am unsure about: how to extract the view state when it changes; storing it in localstorage; and then restoring it when Monaco is loaded. Although I am aware of saveVie ...

Linting error: Unable to access properties of an undefined object (isStrict)

While setting up ESLint in an Angular project, I encountered an error when running the linter: Oops! Something went wrong! :( ESLint: 8.56.0 TypeError: Cannot read properties of undefined (reading 'isStrict') Occurred while linting C:\User ...

Why does the Material button style take time to apply when my Angular application first loads instead of being immediate?

Inside the Angular application I'm working on, there is a toolbar component that consists of three different links. The first link directs to the main app page, while the other two lead to distinct components within the app. Each link is styled with c ...

data not corresponding to interface

I am encountering an issue that says Type '({ name: string; href: string; icon: IconDefinition; } | { name: string; href: string; icon: IconDefinition; childs: { name: string; href: string; icon: IconDefinition; }[]; })[]' is missing the followin ...

Guarding against Angular routes that do not have a component and may include an

Currently, I am in the process of locking down routes by making an API call to check permissions. The existing routes are as follows: { path: '', children: [ { path: '', component: HomeComponent}, { path: ' ...

Troubleshooting: Issues with Angular 2's default routing system

My Angular 4 app's default route isn't functioning properly. Could it be conflicting with my express routes? Interestingly, the wildcard route seems to be working fine. I'm puzzled as to what the issue might be. Here are my Angular routes: ...

Types are not appearing in @types/node

I have added @types/node to my project. In the index.ts file, the default node modules are being treated as type any. const fs = require('fs'); The type of fs is currently set to any. { "ts-node": { "cwd": "/User ...

Is there a way to deactivate the spin buttons for an input number field?

Is there a way to create an input element with type number in Vue using createElement() in TypeScript and then disable the spin buttons for increment and decrement? I attempted to use the following CSS: input[type=number]::-webkit-inner-spin-button, input ...

Error: Attempting to add types to an object returned from the .map function in JSX Element

When attempting to include the item type in the object returned from the .map function, I encountered a JSX error. I tried specifying item: JSX.Element as the Item type, but this didn't resolve the issue. Can someone provide clarity on this matter? Th ...

Is it recommended to keep Angular properties private and only access them through methods?

I'm starting to get a bit confused with Angular/Typescripting. I originally believed that properties should be kept private to prevent external alteration of their values. Take this example: export class Foo{ private _bar: string; constructor(pr ...

Developing an Angular application and deploying it onto the server

I've been working on an angular6 application and I need to create a build to test it on my server. Currently, when I use ng server, the application runs without any errors in my browser. c:\Users\emiry\Desktop\Angular\Proje ...

acquire tabulations from every single document within the templates on DocuSign

When using Docusign, it is possible to retrieve tabs data for a specific document within a template by specifying the documentId. However, I have not been able to locate a method to obtain tabs data for all documents contained within a template. ...

Issue with ngStyle function in Internet Explorer

Within my Angular 4 application, I have defined styles as shown below: [ngStyle]="{'border': getInterleaveColor(i)}" The following function is also included: getInterleaveColor(auditNumber) { var borderProperties = '2px solid'; ...

Modifying text input in Angular

I am working on an Angular form that includes a text input which I would like to be able to edit by clicking on the edit button. Within the form, there are 3 buttons available: edit, cancel (which discards changes), and save (which saves changes). When t ...

What modifications need to be made to the MEAN app before it can be deployed on the server?

Following a tutorial on Coursetro, I was able to successfully build an Angular 4 MEAN stack application. However, when it comes to deploying the app on a server running on Debian-based OS, I am facing some challenges. The application should be accessible o ...

Tips for avoiding Angular routing when clicking on a Bootstrap tab link

I'm working on creating a bootstrap tab, but I'm running into an issue. Every time I click on the tab links, angular seems to be handling its own routing and redirecting me to a different route. What I really want is for the tab content to open u ...

Tips for preventing duplicate entries in an AG Grid component within an Angular application

In an attempt to showcase the child as only 3 columns based on assetCode, I want to display PRN, PRN1, and PRN2. Below is the code for the list component: list.component.ts this.rowData.push( { 'code': 'Machine 1', &apo ...

Error Message: "Module not found - Module TS2307 cannot be located

When I try to open a Typescript project in VSCode, I encounter the error message "ts2307 Cannot find module 'react' or its corresponding type declarations". However, everything works fine when I use WebStorm. The project was created using Create ...