-1

I am using Angular 7 and would like to add html element by using Javascript. Here is the example. "<"img [src]={{address}}">"

I could create regular html like below code

However for Angular, I need to add [src]={{address}}.

Is there any way to add like that?

let img = document.createElement('img');
img.src = "......";
Patrick.L
  • 33
  • 9
  • No, offense, but why do you want to do that? Are you sure there's no "angular way" to do this? –  Jan 15 '19 at 19:17
  • If you haven't already, take some course on Angular and fully understand all that the framework offers and how to do things the 'Angular Way'. As a general rule, if you're trying to inject things into the DOM behind Angular's back, then you're using the framework wrong, and you want to not fight the framework. Ultimate Angular offers some great courses, as does Udemy, and there are a lot of great resources online to help you learn the best way to use the frameworks. – Stephen R. Smith Jan 15 '19 at 20:58

2 Answers2

1

Do not see the case why doing it. You can create and add an element to DOM but you should then take care of updating src by your own. Angular doesn't care of elements it hasn't created.

If you want to do it anyway then you can create a template ref on parent element where you would like to add to: <div #container>... </div> in you component's template.

Then in your typescript file where component is defined you need to query this container with @ViewChild('container') container: ElementRef and after it you can add it to this one:

let img = document.createElement('img');
img.src = this.srcProp;
this.container.nativeElement.appendChild(img);

But be careful that it will just be your headache. Try to avoid such implementations

Danil Gudz
  • 2,233
  • 16
  • 16
0

Do you try something like:

<img src="{{someAddrs | safeHtml}}">

P.S. I was inspired by (you can find there used pipe): How to bind raw html in Angular2

P.S.2 I never try angular 7, so please don't me mad on me

KondzioSSJ4
  • 220
  • 4
  • 12