user2828442
user2828442

Reputation: 2515

Adding dynamic HTML from component to HTML is removing a property / attribute

I am trying to add html from editpage.ts to editpage.html

editpage.ts

var strHTML = '<p [contentEditable]="contentEditable" >abc<p>';
this.possibleHTML = strHTML;
 this.possibleHTML = this.possibleHTML.map(value => this._sanitizer.bypassSecurityTrustHtml(value));

editpage.html

<div  id="main-wrapper">   
    <content *ngIf="possibleHTML">
           <div [innerHtml]="possibleHTML"></div>
    </content>
</div>

When this is inserted, then in developer tools, it looks like this

<h1 _ngcontent-c2>Hii<h2>

My [contentEditable]="contentEditable" attribute is gone. I need to inject HTML dynamically and I need this attribute to change text.

Edit

My component.ts:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-filemanager',
  templateUrl: './filemanager.component.html',
  styleUrls: ['./filemanager.component.css']
})
export class FilemanagerComponent implements OnInit {

  constructor() { }

  ngOnInit() {
this.document.getElementById("main-wrapper").innerHTML += "<p [contentEditable]="contentEditable" >abc<p>";
  }

}

Now what I want is, my attribute should not be lost.

Upvotes: 0

Views: 856

Answers (1)

user4676340
user4676340

Reputation:

I faced this issue myself not so long ago. The problem is with contentEditable that won't be added to your tags if you add it dynamically. If you want to add it, you have to use the innerHTML of a HTMLElement.

This means you can either use a @ViewChild decorator, or use JQuery to find your element. But it won't work by using Angular binding.

Hope this helps.

EDIT This is the example working in my project :

@ViewChild('itcamStr') itcamStr: ElementRef; 

// ... Doing other stuff in my component 

randomFunction() {
    // ... Doing stuff not related before
    this.itcamStr.nativeElement.innerHTML += this.buildLabel('string', 'type');
}

buildLabel(s: string, type: string): string {
    return `<label class="label label-${type} itcam-label" contenteditable="false">${s}</label>`;
}

EDIT 2 Here is a fully working component :

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'my',
  template: '<div #child></div>',
})
export class MyComponent implements OnInit {
    @ViewChild('child') child: ElementRef;

    ngOnInit() {
        this.child.nativeElement.innerHTML = `<p contenteditable>Editable Content</p>`;
    }
}

In your HTML page you juste have to do <my></my>.

Upvotes: 1

Related Questions