0

I want to append htmlString in a div tag.

app.component.ts file,

public htmlString:string = '';

this.htmlString:string = '<img id="img" src="assets/imgages/image.jpg">
<script>
  document.getElementById("img").onclick = function(){
      alert('click on image');
  };
</script>'; 

app.component.html

 <div></div>

I have used below code but script return as a plain text.

<div [innerHTML]="htmlString"></div>

How to solve it?

2 Answers 2

3

You can't do that. Angular ignores the <script> tag altogether. From the docs:

HTML is the language of the Angular template. Almost all HTML syntax is valid template syntax. The <script> element is a notable exception; it is forbidden, eliminating the risk of script injection attacks. In practice, <script> is ignored and a warning appears in the browser console

To display content based on a click event you can do something similar to:

.ts

export class AppComponent {
  displayData: boolean;
  content: string = 'Something to be displayed on click event';

  appendData() {
    this.displayData = true;
  }
}

.html

<img id="img" src="assets/imgages/image.jpg" (click)="appendData()">

<div *ngIf="displayData">
  {{content}}
</div>

Here's the stackblitz for the same.

Sign up to request clarification or add additional context in comments.

3 Comments

Edited the answer to include a trivial example. (The code shared can be made shorter but it's easier to read)
If Angular is prohibiting it; then IMO it's for a reason and I don't think we should try to bypass it.
If the answer helped you; do consider upvoting/accepting it. Thanks!
0

As a simple workaround you can try like this:

HTML:

<div (click)="showAlert()">
  <div [innerHtml]="htmlString"></div>
</div>

TS:

 htmlString: any = '<img id="img" src="assets/imgages/image.jpg">'

 showAlert(){
    alert('click on image');
 }

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.