Angular [innerHtml]: how to render additional elements inside an element with [innerHtml] directive
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
Style not working for innerHTML in Angular
This behavior you're getting is normal. The class added to innerHTML
is ignored because by default the encapsulation is Emulated
. Which means Angular prevents styles from intercepting inside and outside of the component.
You should change the encapsulation to None
in your component.
This way, you'll be able to define classes wherever you want: inside styles
or in a separate .css
, .scss
or .less
style-sheet (it doesn't matter) and Angular will add them to the DOM automatically.
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'example',
styles: ['.demo {background-color: blue}'],
template: '<div [innerHTML]="someHtmlCode"></div>',
encapsulation: ViewEncapsulation.None,
})
export class Example {
private someHtmlCode = '';
constructor() {
this.someHtmlCode = '<div class="demo"><b>This is my HTML.</b></div>';
}
}
How can I resolve "safeHtml pipe not working" in Angular 8
You should use a simple ViewChild()
.
HTML:
<div #simpleDiv></div>
COMPONENT
import { Component, ViewChild, AfterViewInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html'
})
export class AppComponent implements AfterViewInit {
@ViewChild('simpleDiv', { static: true }) simple;
ngAfterViewInit() {
this.simple.nativeElement.innerHTML = 'AAA';
}
}
stackblitz example
Be aware however that there are very few legitimate reasons to use innerHTML directly in angular. and whatever it is you're trying to achieve. can most likely be done in a safer more, 'angularish' way.
wherever I see innerHTML in a modern framework application, it almost always ends up being some web developer who tries to achieve something, in the tools he already knows, going around the framework, rather than learning how to do it properly using the framework.
Alas, I can be wrong.
Related Topics
Change Name of Uploaded File on Client
Add Hyphen After Every Fourth Character in a String Seperated by Comma
How to Tell Chrome Web Debugger to Show the Current Mouse Position in Page Coordinates
How to Refresh Select Option List After Ajax Response
Button Enabled and Disabled Based on Checkbox Is Checked or Not
How to Find Nearest Location Using Latitude and Longitude from a Json Data
Remove Duplicate Objects from Json Array
How to Remove the X-Axis from a Bar Chart Produced by Google'S Visualization API
Lodash Group by Multiple Properties If Property Value Is True
Increase and Decrease Number With JavaScript and Two Buttons Up and Down
How to Build Pdf File from Binary String Returned from a Web-Service Using JavaScript
How to Use Zindex in React-Native
How to Clear All Input Fields in Bootstrap Modal When Clicking Data-Dismiss Button
Destroy Chart.Js Bar Graph to Redraw Other Graph in Same <Canvas>
Uploading Multiple Files Using Formdata()
Ng2-Smart-Table Bind 'Add New' Button Event to an External Button
In Nest.Js, How to Get a Service Instance Inside a Decorator