There is a DIV in Angular template:
<div #parent [innerHTML]="content"></div>
and in .ts file
let content = 'test1 test2 test3'
Now I’m creating new DIV:
const newDiv = this.renderer.createElement('div') as HTMLDivElement
newDiv.innerHTML = 'plug'
newDiv.addEventListener('click'......)
Goal is to have inside #parent:
test1 <div>plug</div> test2 test3
and new div should have working listener.
How?
Manipulating innerHTML as string directly is not a solution: div exists but it is invisible for Angular engine.
KBuk is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
6
Ugly solution:
//have some dynamic html which angular engine is not aware of:
let content = 'apple tree or <span>any other <b>dynamic</b></span> text'
//create temporary div or any other DOM element by string:
let tempInjector = '<div id="ref1"></div>'
// make new string and put the injecor into old string using brutal text/non-dom methods:
let nc = content.substring(0, 5) + tempInjector + content.substring(5, content.length)
// create DOM object in proper way with angular renderer, and assign some listener+content:
const newEl = this.renderer.createElement('div') as HTMLDivElement;
this.renderer.listen(newEl, 'click', (event) => {console.log('this is angular aware DOM');})
newEl.innerHTML = '[ANGULAR AWARE OBJECT]'
//(private cdr: ChangeDetectorRef) this is imporant step!
this.cdr.detectChanges()
// now get the "injector" as dom object using id:
const el = document.getElementById('ref1')
if (el) {
// insert Angular object after "injector"
el?.insertAdjacentElement('beforebegin', newEl)
// then remove injector.
el.remove()
}
//update variable connected with html:
this.content = nc
Done. Now your angular aware DOM node is inside html with working listener and other angular-like things.
KBuk is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.