2

I want to insert a widget from Tradingview into my Angular 2+ ASP.NET Core website.

<!-- TradingView Widget BEGIN -->
<script type="text/javascript" src="https://s3.tradingview.com/tv.js">
</script>
<script type="text/javascript">
new TradingView.widget({
  "width": 980,
  "height": 610,
  "symbol": "NASDAQ:AAPL",
  "interval": "D",
  "timezone": "Etc/UTC",
  "theme": "Light",
  "style": "1",
  "locale": "en",
  "toolbar_bg": "#f1f3f6",
  "enable_publishing": false,
  "allow_symbol_change": true,
  "hideideas": true
});
</script>
<!-- TradingView Widget END -->

So, I tried two ways. Option 1 using the DomSanitizer. I initialize the above script into as a string variable in my component. Then in my template I assign:

In component:
myScriptInComponent = the script above;

In my template

<div [innerHtml]="script">
</div>

After which OnInit I call:

this.script= this.sanitizer.bypassSecurityTrustScript(this.mySriptInComponent);

In this case I get an error. Required a safe HTML, got a Script

Then I tried inserting the js file from https://s3.tradingview.com/tv.js into my application with webpack by using webpack --config webpack.config.vendor.js.

After that I simply imported this js file into my component and called the new TradingView.widget ...etc. onInit but here I'm getting an error which says cannot read property 'widget' of undefined.

Kind of stuck with what to try next. Would really appreciate any hints. Thank you.

Yuri Zolotarev
  • 721
  • 9
  • 23

1 Answers1

0

So after I have read and tried hopelessly about everything there is on DOM manipulation the only thing that worked was actually postscribe which I ignored at first.

First install using npm install --save postscribe, then add to webpack.config.vendor.js and run webpack --configure webpack.config.vendor.js after which in your template create a div with an id. In your component do the following:

import * as postscribe from 'postscribe';

ngAfterViewInit() {
     postscribe('#yourDivId', '<script>yourscriptstring</script>');
{

Good luck!

Yuri Zolotarev
  • 721
  • 9
  • 23