Home > Net >  Link for specific in word in a paragraph in Angular\Typescript "section"
Link for specific in word in a paragraph in Angular\Typescript "section"

Time:02-17

I have a specific paragraph and text is specified in "Section" in typescript and I would like to add a link to a specific word in it. For example, "Please click here for more information". In this sentence, I would link "Click here" to be a hyperlink

Currently my typescript file has following section and HTML file uses ngFor for looping through sections and displaying content on the UI -

test = {
sections: [
      {
        title: 'Foo',
        description: `Please click here for more information`
      }
]
}

HTML file -

<div *ngFor="let section of test.sections">
            <h4>{{section.title}}</h4>
            <p>{{section.description}}</p>
           
        </div>

I am a beginner and not sure how to add link specifically for "Click here". Can someone please help?

CodePudding user response:

Simply add the link tags to the string of description using backticks.

Please <a href="#">click here</a> for more information

If you want to code links dinamically, then you should check string manipulation in typescript.

Typescript - Strings

CodePudding user response:

To make the link clickable, you first need to have an anchor tag within description property of sections array. Example:

sections: [{
  title: 'Foo',
  description: `Please <a href="...">click here</a> for more information`
}]

Once you have made such adjustment you can use DOMSanitizer to render dynamically generated HTML content. Angular by default will ignore such links because of security concerns. You can read more on this - https://angular.io/api/platform-browser/DomSanitizer

In order to use DOMSanitizer, I would recommend to create a pipe and use it in template. Here is how you would do it. (Snippet referenced from thread)

  1. Create a file sanitized-html.pipe.ts

    import { Pipe, PipeTransform } from '@angular/core';
    import { DomSanitizer } from '@angular/platform-browser';
    
    @Pipe({
      name: 'sanitizedHtml'
    })
    export class SanitizedHtmlPipe implements PipeTransform {
      constructor(private sanitized: DomSanitizer) {}
      transform(value: any): any {
        return this.sanitized.bypassSecurityTrustHtml(value);
      }
    }
    
  2. Add this file to AppModule (or the module in which you want to use this pipe)

    @NgModule({
      declaration: [SanitizedHtmlPipe],
    })
    
  3. Use this pipe within HTML template

    <div *ngFor="let section of test.sections">
      <h4>{{ section.title }}</h4>
      <p>{{ section.description | sanitizedHtml }}</p>
    </div>
    
  • Related