在父DIV的特定索引处插入DOM元素

问题描述 投票:0回答:1

Angular 模板中有一个 DIV:

<div #parent [innerHTML]="content"></div>
并在 .ts 文件中

let content = 'test1 test2 test3'

现在我正在创建新的 DIV:

const newDiv = this.renderer.createElement('div') as HTMLDivElement

newDiv.innerHTML = 'plug' 

newDiv.addEventListener('click'......)

目标是在#parent 内部:

test1 <div>plug</div> test2 test3
新的 div 应该有工作监听器。

如何?

直接将innerHTML作为字符串操作并不是一个解决方案:div存在,但对于Angular引擎来说是不可见的。

javascript angular dom
1个回答
0
投票

丑陋的解决方案:

//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

完成。现在你的 Angular 感知 DOM 节点位于 html 中,并带有工作监听器和其他类似 Angular 的东西。

© www.soinside.com 2019 - 2024. All rights reserved.