I simply need to inject HTML in a div with id
"main-wrapper"
, so in my component.ts i am using this code
import { Component, OnInit, ElementRef,Renderer2,Inject } from '@angular/core';
import { Pipe } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';
@Component({
selector: 'app-editsection',
templateUrl: './editsection.component.html',
styleUrls: ['./editsection.component.css']
})
export class EditsectionComponent implements OnInit {
...//some code
constructor(
@Inject(DOCUMENT) private document: any,
private route: ActivatedRoute,
private elRef: ElementRef,
private el: ElementRef,
private _sanitizer:DomSanitizer
) { }
ngOnInit() {
var strHTML = '<p>abc<p>';
this.document.getElementById("main-wrapper").innerHTML += this._sanitizer.bypassSecurityTrustHtml(strHTML);
...
}
}
When i run the code it says: SafeValue must use [property]=binding: abc
(see http://g.co/ng/security#xss)
Why i need to implement this- Because when i am injecting innerHTML, i am loosing a property contenteditable="true"
Before applying innerHTML, my code looks as shown below:
<h1 _ngcontent-c2 contenteditable="true">Hii<h2>
After applying innerHTML it becomes:
<h1 _ngcontent-c2>Hii<h2>
Please help me resolve the problem
The whole methodology behind angular is anchored on reduction of DOM manipulation via script (such as what you have) as recommended in http://angularjs.blogspot.com.au/2016/04/5-rookie-mistakes-to-avoid-with-angular.html.
So instead of using this:
this.document.getElementById("main-wrapper").innerHTML +=
You should make use of the templating engine / structural directives like
*ngFor *ngIf
inherent in angular.As per your comment:
You are loading a bunch of html from localstorage. In this case, you will have to manipulate the DOM. Ideally i would recommend re-configuration of this architecture for performance purposes as stated in the aformentioned.
1st, load the html into typescript...
2nd insert the html.
drawbacks: css styling does not take effect unless it is defined as a global stylesheet
styles.css
instead ofeditsection.component.css
.