1

I am trying to insert an anchor tag in a string variable. The string will be shown on screen as a link, but it seems to ignore the anchor tag, and only including the value inside the tag. example something turns to just 'something'

private generateAnchors(content: string) {
    let contentToReturn = content;
    if (content.indexOf('@') < 0) return contentToReturn;
    else if (content.indexOf('@') > -1) {
        let tag = content.substring(content.indexOf('@'), content.indexOf(' ', content.indexOf('@')));
        let address = tag.substring(1, tag.length);
        let anchor = '<a href="/home/user/"'+address+'>'+tag+'</a>';
        console.log('found substr: '+tag, ' '+address+' '+anchor);
        contentToReturn.replace(tag, anchor);
        console.log('final string: '+contentToReturn);
    }
    return contentToReturn;
}

How is this done in Angular/TypeScript ?

Jonas Praem
  • 2,296
  • 5
  • 32
  • 53

1 Answers1

2

Did you try to replace:

contentToReturn.replace(tag, anchor);

with:

contentToReturn = contentToReturn.replace(tag, anchor);

String.replace doesn't change your string since it's immutable, it just returns a new one with the replacement done.


Angular Templating

Apart from this little issue, you should consider using Angular's templating mechanics. You should read the documentation to learn this but I'll try to give you an example that fits your particular case.

You'd have one links.component.html file with:

<a href="/home/user/{{address}}">{{tag}}</a>

Or maybe a loop if you need several of them:

<div *ngFor="let link in links">
  <a href="/home/user/{{link.address}}">{{link.tag}}</a>
</div>

And a corresponding links.component.ts with the corresponding elements:

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

@Component({
  selector?: "app-links-component"
  templateUrl: "links.component.html"
})
export class LinksComponent {
  address: string;
  tag: string;

  constructor() {}

  // ts logic to fill address/tag information
}

Or an array in the second case:

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

@Component({
  selector?: "app-links-component"
  templateUrl: "links.component.html"
})
export class LinksComponent {
  links: Link[] = [];

  constructor() {}

  generateAnchors(address: string, tag: string) {
    // You can bind this method to a form submit or something.
    this.links.push(new Link(address, tag));
  }
}

N.B.: Since this is all written by heart, there might be typos here and there...

Adrien Brunelat
  • 4,492
  • 4
  • 29
  • 42