【发布时间】:2021-03-22 01:59:46
【问题描述】:
我想显示一个带有标题和内容的日志。
使用以下代码,li 元素插入到 DOM 中,右侧为 className,但样式不显示。
这是在一个 Angular 组件中,我认为这可能是错误的根源。这只是一个带有 html 的基本新应用程序:<app-example></app-example>
注意:如果我在 html 中手动插入一个元素,它会正确显示。
我注意到的唯一区别是从 javascript 插入的 li 元素没有 _ngcontent-cxr-c40。
HTML:
<ul class="d-flex f-column log-list" id="log-list">
<li id="log-item" class="log-message">
<span class="log-message-title">TEST</span>
</li>
</ul>
这是向日志添加元素的函数:
private addLogElement(title: string, message: string): void {
const newNode = document.createElement('li');
newNode.className = 'log-message';
const newNodeTitle = document.createElement('span');
newNodeTitle.className = 'log-message-title';
const headerText = document.createTextNode(title);
newNodeTitle.appendChild(headerText);
newNode.appendChild(newNodeTitle);
const parentDiv = document.getElementById('log-list');
const childDiv = document.getElementById('log-item');
parentDiv.insertBefore(newNode, childDiv);
}
【问题讨论】:
-
您的代码应该可以工作,但它不是“Angular 方式”。在这个数组上使用一个数组和一个*ngFor:angular.io/guide/structural-directives,你只需要在数组中添加一个元素
-
是的,您不应该那样直接修改文档。改为采用数据驱动的方法。
-
在操作 dom 时使用 renderer2 可能有一些好处,但它应该只适用于 JS。查看digitalocean.com/community/tutorials/angular-using-renderer2 了解更多信息
标签: javascript html css angular dom