An element with the [innerHtml] directive just seems to add the declared html string inside that element, and nothing more;
through this stackblitz , i was trying to add something inside such an element, to no avail;
<div [innerHTML]="safeHtml(item.isi)"><p>new word - will not show</p></div>
Is there a way to add some more HTML inside an element with the [innerHtml] directive? In other words, how can i make the stackblitz in the example work?
why are you using [innerHTML] since your item.isi is not an html element; we use innerHTML to render a html result; like if your item.isi is <p>My name</p>
; if it is not a html element no use of using innerHTML, you can simply use {{item.isi}} inside your div, so you can render other html elements also
you can try by using ElementRef
, if you want to append element not want to replace full html ,
html
<div #Container>
add here
</div>
ts file
export class AppComponent implements AfterViewInit {
@ViewChild('Container') container: ElementRef ;
content = [
{judul: "Judul 1", isi:"<div id='title_1'>Isinya</div>"},
{judul: "Judul 2", isi:"<div id='title_2'>pranay</div>"},
];
ngAfterViewInit() {
this.content.forEach( (item,index) =>{
this.container.nativeElement.insertAdjacentHTML('beforeend', `<div id="title${index}">${item.judul}</div>`);
this.container.nativeElement.insertAdjacentHTML('beforeend', `${item.isi}`);
});
}
however elementref is not recommended way.
output of above code
you can see it adding content after , add here one by one
Find : Working Demo
Instead of using function in your component (its not working as your html-template trying to pass html to your typscript file) , you should create pipe as below
html.pipe.ts
import { Component, Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({
name: 'html'
})
export class HtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {}
transform(value) {
return this.sanitized.bypassSecurityTrustHtml(value);
}
}
and use it like
html
<div *ngFor="let item of content">
<h3 [innerHTML]="item.judul | html ">add</h3>
<div [innerHTML]="item.isi | html "><p>new word</p></div>
</div>
Find : Working Demo
As i understand your question, using inner html replaces the inner html. Therefore the old value is replaced by the value from your object.
i understand you are following this approch as you want to display the value from the object.
So a better approach is using pipes. May be. Just check this answer. If it helps. Click here
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.