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;
      } 
    )
  }

https://i.sstatic.net/hzAew.png

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

What is the alternative method for enabling cross-origin authentication if CORS wildcard is not permitted for authentication?

I encountered a CORS error while making an AJAX request using HttpClient. The error arises when trying to receive res.cookie in the response. Here is some background information on my CORS policy: app.use(cors()); app.options('*',cors()); var al ...

Strategies for efficiently managing multiple subscriptions in an Angular form using minimal code and best practices

I am currently working on an Angular form that includes multiple select options managed by Subscriptions. However, I find myself writing a lot of code for each Subscription and would like to improve this process. Could someone provide some best practices ...

Angular Test Error: Refactoring requires a source file to be present

Trying to execute the command ng test, I encountered an error message. How can this issue be resolved? I am unsure of its meaning. ERROR in Must have a source file to refactor. To eliminate this warning, use "ng config -g cli.warnings.versionMismatc ...

Trouble accessing images from database in Angular 2 with Firebase

Recently, I've integrated an image upload feature for my database using the following function: private saveFileData(upload: Upload): void { this.firebaseAuth.authState.subscribe(auth => { this.db.list(`uploads/${auth && auth.email && au ...

Having trouble creating a dynamic form in Ionic

I am in need of creating a dynamic form. Here is the desired output: {"laboratories":[{"colArr":[{"col":"11"},{"col":"22"},{"col":"33"}]},{"colArr":[{"col":"5"},{"col":"423"}]}]} The key laboratories represents the number of rows. Each row contains the k ...

Angular Compilation Blocked Due to Circular Dependency Error

Currently, I am utilizing WebStorm as my IDE to work on a personal project that I envision turning into a game in the future. The primary goal of this project is to create an Alpha version that I can showcase to potential employers, as I am actively seekin ...

Setting a value in Ionic 3 HTML template

Attempting to assign a value in an Ionic 3 template from the ts file while also adding css properties but encountered an issue. PROBLEM Error: Uncaught (in promise): Error: No value accessor for form control with name: 'image' Error: No va ...

Encountering an issue with Typescript Vue class-based components in Laravel Mix: issue arises when attempting to set property 'render' on an undefined object

I have been using Laravel Mix to compile my Vue components, incorporating TypeScript and class-based components. Each class is exported from the component, and every component is required by the context in the main application script. However, during rende ...

Struggling to extract specific information from a json array using Angular, my current approach is only retrieving a portion of the required data

My JSON structure is as shown in the image below: https://i.stack.imgur.com/5M6aC.png This is my current approach: createUIListElements(){ xml2js.parseString(this.xml, (err, result) => { console.log(result); this.uiListElement = result[ ...

Strategies for passing multiple props to a function in React using TypeScript, such as useState([]) and useState(boolean)

Dealing with API Structure { "default": [ { "id": 1, "name": "A" }, { "id": 2, "name": "B" }, { "id": 3, "name" ...

Adding a CSS class to a component element

I am working with an angular component that looks like this: export class HeaderMainComponent { } This is the HTML structure: <header> <nav> <li>Link 1</li> <li>Link 2</li> </nav> </header> ...

Navigate to the main page of the routing module within Angular

Iā€™m struggling to find an easy way to achieve this task. Here is a snippet from my app-routing.module.ts file: { path: 'items', loadChildren: () => import('./items/items.module').then(m => m.ItemsModule) }, And in items-routi ...

The header code in Angular 6 does not get triggered when working with the router

After successfully validating the username and password, I perform the following action: this.router.navigate(['./home']); Each page includes a header with the following content: <ng-container *ngIf='isAuthenticated'> <li c ...

The latest update for angular-devkit/build-angular (version 0.13.4) has brought a new issue with the configuration output. It seems that there is an unrecognized property

After upgrading a project from angular-devkit/build-angular v0.11.4 to v0.13.4, an error is now appearing: Invalid configuration object. Webpack has been initialised using a setup that does not align with the API schema. - configuration.output contains a ...

After being awaited recursively, the resolved promise does not perform any actions

When working with the Twitter API, I need to make recursive method calls to retrieve tweets since each request only returns a maximum of 100 tweets. The process is straightforward: Call the function and await it Make an HTTP request and await that If the ...

Angular 5 Web-Based EPUB Reader

Just getting started with Angular 5 and I'm looking to display an epub file on a page without resorting to iframes. Any suggestions on how to achieve this? ...

What is the syntax for declaring a boolean or object type?

Is it possible to create a variable in TypeScript that can hold either true/false or an object of booleans? I'm still learning TS and would like some input on this syntax. variableA: { a: boolean, b: boolean } | boolean I found a workaround for now, ...

Angular 2 routing allows us to seamlessly display multiple components within the same application

After logging in with the login component, I encountered an issue where both the login and mainpage components were displaying on the same page in Angular 2. In my app.module.ts file: import { NgModule } from '@angular/core'; import { Brow ...

Combining Multiple .ts Files into a Single File: A Simplified Application Structure with TypeScript 1.8

Currently, I am in the process of developing an Electron application and I have decided to implement TypeScript for this project. While TypeScript essentially boils down to JavaScript in the end, my familiarity with it makes the transition seamless. As of ...

Load Angular template dynamically within the Component decorator

I am interested in dynamically loading an angular template, and this is what I have so far: import { getHTMLTemplate } from './util'; const dynamicTemplate = getHTMLTemplate(); @Component({ selector: 'app-button', // templat ...