0

I am creating a mention directive.When user trying to insert something on textarea my directive will trigger and shows the users list.On save this will return the value as text.

Eg: Good morning @alice.Today is @bob 's birthday.

I would like to show this like a post.So want to add hyperlinks to specific users.

My first attempt was to store the mentioned users list in array and then filter out, then form hyperlinks dynamically.But that was a failure had problems with multiple users.

Now i think it is better to convert the text to Html and save as string.Then call on [innerHTML].

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 converted: string;
  text: string;
  constructor() {
    this.text = 'Good morning @alice.Today is @bob 's birthday.';
    this.converted = this.textToHtml(this.text);
  }
   textToHtml(text: string) {
    return text.replace(/@([a-z\d_]+)/ig, `<a href="http://localhost:4200/profile/$1">$1</a>`);
  }
}

I have an object with profile number respective to the users

let userList = {
  'alice':100,
  'bob': 101
}

How can i modify the regex and return the name with hyperlink points to profile?

Eg:

<a [routerLink]="['/profile', ${userId of user}]">${name}</a>
The Hungry Dictator
  • 3,444
  • 5
  • 37
  • 53
Amal Shehu
  • 119
  • 2
  • 14

1 Answers1

0

That's not possible because like this, because the routerLink won't be parsed. You can however create a new Component which does this work for you. Preferably you would also need to create a UserService which does the work of obtaining the user list, and getting the user by username:

@Component({
  selector: 'user-router-link',
  template: `
    <a [routerLink]="'/profile/' + user.id" [innerHtml]="'@' + user.name"></a>
  `
})
export class UserRouterLink {

  @Input()
  public username: string;

  public get user(): User {
      return this._userService.getByUsername(this.username);
  }

  constructor(private _userService: UserService) {}

}

Now you need to find a way to have your parent component have a template like:

Good morning <user-router-link username="alice"></user-router-link>. 
Today is <user-router-link username="bob"></user-router-link>'s birthday.
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
  • Will this solution works for dynamic content? I think it won't. – Amal Shehu Aug 08 '17 at 08:25
  • Dynamic content is not recommended in angular. You should find different means to do this. If you cannot, i suggest looking [here](https://angular.io/guide/dynamic-component-loader) – Poul Kruijt Aug 08 '17 at 08:35