Angular2 innerHTML removes property, help needed to use DomSanitizer

I just need to inject HTML into the div using id "main-wrapper", so in my component.ts component i use 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 should use [property] = binding: ABC

(see http://g.co/ng/security#xss )

Why do I need to implement this? Because when I insert innerHTML, I lose the propertycontenteditable="true"

Before applying innerHTML, my code looks like this:

<h1 _ngcontent-c2 contenteditable="true">Hii<h2>

After applying innerHTML it becomes:

<h1 _ngcontent-c2>Hii<h2>

Please help me solve the problem.

+4
source share
1

angular DOM- script (, , ), http://angularjs.blogspot.com.au/2016/04/5-rookie-mistakes-to-avoid-with-angular.html.

, DOM . angular 2 API, , . API .

...

DOM, .


, : this.document.getElementById("main-wrapper").innerHTML +=

/ , *ngFor *ngIf, angular.

// .html
<div class="main-wrapper"><p *ngIf="showabc">abc</p></div>
// .ts
var showabc: Boolean = true;

:

html localstorage. DOM. , .

html typescript...

public possibleHTML: Array; 
constructor(private sanitizer: DomSanitizer){}
ngOnInit(){  
   this.possibleHTML = loadContentFromLocalStorage();
   this.possibleHTML = this.possibleHTML.map(value => this.sanitizer.bypassSecurityTrustHtml(value));
}

html.

<div class="main-wrapper">
    <content *ngIf="possibleHTML">
       <div *ngFor="let html of possibleHTML">
           <div *ngIf="html.makevisible" [innerHtml]="html"></div>
       </div>
    </content>
</div>

: CSS- , styles.css editsection.component.css.

+2

Source: https://habr.com/ru/post/1679303/


All Articles