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 = "......";
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
Do you try something like:
<img src="{{someAddrs | safeHtml}}">
PS I was inspired by (you can find there used pipe): How to bind raw html in Angular2
PS2 I never try angular 7, so please don't me mad on me
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.