Search code examples
angulartypescripthyperlink

How to create a hyperlink in Typescript file? Angular 16+


I have a consts.ts file in my project, now.. I have

export const LINK1 = <a href='https://sample.com/'>LINK 1</a>;

It doesn't work. I want to have a hyperlink text which is "LINK 1"

export const LINK1 = `<a href='https://sample.com/'>LINK 1</a>`;

I want to have a hyperlink text which is "LINK 1"


Solution

  • Instead of storing the actual html in the string, why not just store the URL in the constants.

    export const LINK1 = 'https://sample.com/';
    

    Then in the component you can store this in a variable and use it on the HTML.

    TS

    import { LINK1 } from './path-to-constants';
    ...
    
    ...
    @Component({ ... });
    export class SomeComponent {
        link = LINK1;
        ...
        
    

    HTML:

    <a [href]="link">LINK 1</a>
    

    If you definetly want to store the HTML as a string, then you can use [innerHTML] to convert the string to HTML.

    The downside of this approach is that, angular features like property binding, event binding do not work using this method.

    CONSTANTS

    export const LINK1 = '<a href='https://sample.com/'>LINK 1</a>';
    

    TS

    import { LINK1 } from './path-to-constants';
    ...
    
    ...
    @Component({ ... });
    export class SomeComponent {
        link = LINK1;
        ...
        
    

    HTML:

    <span [innerHTML]="link"></span>