1

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"

2
  • Please look at this answer also. stackoverflow.com/a/41675806/1792984 Commented Jun 21, 2024 at 3:58
  • export const LINK1 = "<a href='https://sample.com/'>LINK 1</a>";, see that you always can enclosed an expression with singles quotes using double quotes -viceverse is true also- Commented Jun 21, 2024 at 12:20

2 Answers 2

0

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>
Sign up to request clarification or add additional context in comments.

Comments

-1

I don't see a good reason that LINK1 is a constant. In my opinion, as you've chosen Angular for a development framework, LINK1 should be a component. So, you could use it wherever you want like <app-link1 />, and it will be handled properly and safely by the framework.

Here is an example component

// link1.component.ts
@Component({
  selector: 'app-link1',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './link1.component.html',
  styleUrls: ['./link1.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class Link1Component {}
<!-- link1.component.html -->
<a href='https://sample.com/'>LINK 1</a>
<!-- example usage of the component -->
...
<app-link1 />
...

This way you have the flexibility to expose the href and the link text as inputs whenever you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.