Angular 8: Master the art of HTML binding

I am facing an issue with displaying HTML content in Angular 8.

**Note: The HTML template I receive from the database as JSON data needs to be displayed in Angular. I am fetching this template and saving it in a variable (e.g., plot), then passing that variable to

this.myTemplate = this.sanitizer.bypassSecurityTrustHtml(this.plot)

For demonstration purposes, I have provided a sample HTML template similar to the data fetched from the database.

HTML:

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

app.component.ts:

import { Component, OnInit} from '@angular/core'; 
import { DomSanitizer, SafeHtml} from '@angular/platform-browser';

@Component({
  selector: 'app-data-decomposition',
  templateUrl: './data-decomposition.component.html',
  styleUrls: ['./data-decomposition.component.css']

})

export class DataDecompositionComponent implements OnInit {

myTemplate:SafeHtml;

constructor(private sanitizer: DomSanitizer) { }

this.myTemplate = this.sanitizer.bypassSecurityTrustHtml(`<html>
  <head>
    <!-- Load plotly.js into the DOM -->
    <script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
</head>

<body>
<p>plot come below...</>
    <div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>

  <script type="text/javascript">
  var data = [
    {
      x: ['giraffes', 'orangutans', 'monkeys'],
      y: [20, 14, 23],
      type: 'bar'
    }
  ];

  Plotly.newPlot('myDiv', data);

  </script>
  </body>
  </html>`);

}

Despite running the code, only the content within the <p> tag "Plot come below.." is visible on the Angular front-end. The Plotly chart within the <script> tag is not being displayed. Any suggestions on where I might have made a mistake would be greatly appreciated.

Answer №1

Make sure to move your script tags to the index.html file instead of keeping them in the component. Remember to properly close all HTML tags for better code structure!

<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
<script type="text/javascript">
  var data = [
    {
      x: ['giraffes', 'orangutans', 'monkeys'],
      y: [20, 14, 23],
      type: 'bar'
    }
  ];

  Plotly.newPlot('myDiv', data);

  </script>

Check out this example: https://stackblitz.com/edit/angular-83tffr

Answer №2

Unfortunately, your current approach won't work. Firstly, attempting to insert an entire HTML page into a div is not feasible. Secondly, it's essential to initiate the scripts before loading the HTML content within your component.

Incorporate the component's HTML code in either app.component.html or any other Angular component you have created. Consider generating a new component and importing it into your app-component for better organization.

<p>plot displayed below...</>
    <div id='myDiv'><!-- The Plotly chart will be rendered inside this DIV --></div>

If you are unable to place the script in index.html as Çağrı TAÇYİLDİZ has suggested,

Alternatively, try implementing the following method:

import { Component, OnInit} from '@angular/core'; 
import { DomSanitizer, SafeHtml} from '@angular/platform-browser';

@Component({
  selector: 'app-data-decomposition',
  templateUrl: './data-decomposition.component.html',
  styleUrls: ['./data-decomposition.component.css']

})

export class DataDecompositionComponent implements OnInit {


constructor() { }

   public loadScript(url) {
        let node = document.createElement('script');
        node.src = url;
        node.type = 'text/javascript';
        node.async = true;
        node.charset = 'utf-8';
        document.getElementsByTagName('head')[0].appendChild(node);
    }


ngOnInit(){
  this.loadScript('https://cdn.plot.ly/plotly-latest.min.js');
}


}

You can embed the script tags within /data-decomposition.component.html, but it is recommended to include them in your index.html file, or alternatively, create a new JS file and import it in index.html, or use the loadScript method within the class to facilitate importing.

<script type="text/javascript">
  var data = [
    {
      x: ['giraffes', 'orangutans', 'monkeys'],
      y: [20, 14, 23],
      type: 'bar'
    }
  ];

  Plotly.newPlot('myDiv', data);

  </script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Stylesheets do not have the capability to support template tags

Imagine you have created a stylesheet in Django within the static files and everything is working smoothly. However, when trying to use the following line, an error occurs: .PostProfilePic { width: 50px; height: 50px; border-radius: 50%; background ...

Error message: When working with Protobuf, an uncaught reference error occurs because the 'exports

Currently, I am in the process of configuring protobuf to work with typescript. According to the official Google Documentation, all that is needed is to execute npm install google-protobuf and then to include require('google-protobuf'). Unfortu ...

Why is my CSS not recognizing the animation I specified for it to play?

I can't seem to get the simple animation I added to my code working properly. <div class="phone-center"> <div class="phone"> </div> </div> .phone-center { display: flex; justify-content: ce ...

"Attempting to verify a JSON Web Token using a promise that returns an object not compatible with the specified

Learning about Typescript has been quite a challenge for me, especially when it comes to using the correct syntax. I have implemented a promise to retrieve decoded content from jwt.verify - jsonwebtoken. It is functioning as intended and providing an obje ...

Trouble arises as the Raspberry Pi GPIO pins refuse to toggle

Encountering an intriguing issue here. I've developed a Python program to regulate the climate of a room with a web interface. While the program functions properly, upon restarting the Raspberry Pi, all GPIO pins are activated. It's only after ac ...

TS2403 error occurs when an unexported variable with an identical name is utilized in multiple files

As a newbie in the world of TypeScript, I am venturing into creating a backend with Node.js (or should I say Node.ts?). Currently, I am in the early stages of setting up my server and exploring the fundamentals. My setup includes ts-node version 8.6.2 and ...

The bootstrap modal is appearing correctly, but the content within it is not displaying properly

I've been working on a website and added a modal for signup. However, when the user clicks on the signup button, the modal appears but the content inside it is not clickable. Can someone please help me with this issue? Here is the code snippet I am us ...

`Resolving CORS error when setting up an AWS Lambda function with API Gateway on AWS`

In the AWS lambda function provided below, I have set it up to call an API that lists all country names. The function is connected to an API Gateway and works as expected when tested with Postman. Here is the code snippet: import axios from 'axios&apo ...

`Manipulating the image source attribute upon clicking`

I need help changing the attr: { src: ...} binding of an img element when a different image is clicked. Here is an example: $(document).ready(function () { var viewModel = { list: ko.observableArray(), showRenderTimes: ...

switching between div and fixed positioning for lightbox functionality

I am working on an HTML file <html> <body> <div #main> <a click to open lightbox> <img> <more images> </a> </div> </body> </html> After the lightbox opens, the code looks like this: <html&g ...

Animating Text with CSS for Different Message Lengths

I have been exploring alternatives to the marquee tag and discovered a way to achieve this through CSS. However, the messages I am working with vary in length. Is there an alternative to setting the '45s' attribute to maybe 100% so that regardles ...

Including my stylesheet with a relative path to easily access the folder from any location

After successfully linking my stylesheet customstyle.css to my index.html, I encountered an issue when copying the folder to another drive - the stylesheet wouldn't get linked. How can I resolve this problem as I need to share the folder with someone ...

Arrange blocks within bootstrap columns using grid css

I have a layout with two columns, each containing two blocks Currently, the mobile order is: 1 2 3 4 But I want it to be: 3 1 2 4 I attempted to use CSS grid but I am unsure how to move block 3 out of column 2. Here's the code snippet: body { ...

Are There Other Ways to Replicate the Actions of an Anchor Link/Target Pseudo-Class?

New Inquiry: Can the onclick attribute within an <a> tag function the same way as the href attribute? In the code snippet below, I have applied <a href="#view"> to all images, and <a id="close-customlightbox" class="lb-animate" href="#!"&g ...

Tips for creating a jasmine test scenario for a function executed within the ngOnInit lifecycle hook

I am finding it challenging to create a successful test case for the code snippet below. In my component.ts file id = 123456; data = []; constructor(private serv: ApiService){} ngOnInint(){ getData(id); } getData(id){ this.serv.getRequest(url+id) ...

Shorten/Alternate coding:

Sometimes, creating the content section of a website can be time-consuming. I recently spent half a day crafting the index page of my website at . However, when attempting to add an additional image to the list of six already present, it turned into a leng ...

Issue occurred while trying to render a React component with Typescript and WebPack

I am in the process of creating a basic React component that simply displays a page saying Hello. However, I'm encountering an error in my console. My compiler of choice is TypeScript. To set up my project, I am following this guide: https://github.co ...

What is the best way to assign a default value in a select dropdown menu without it being a

I have a dropdown with a list of users on my web page: <select class="form-control" name="user"> <#list sbUsers as sbUser> <option value="${sbUser.login}">${sbUser.login}</option> </#list> </select> How ...

What is the reasoning behind defaultValue possessing the type of any in TextField Material UI?

According to the Material UI guidelines, the component TextField specifies that its defaultValue property accepts the type any. I decided to experiment with this a bit and found that in practice, defaultValue actually supports multiple types. You can see ...