在开发 Angular 应用程序时,我反复使用检查器寻找组件选择器(示例:
app-custom-component
)。这让我思考。我可以简单地在 top:0, left:0
上的 Angular 中的每个组件上方显示选择器的值吗?我想在不修改组件的情况下实现这一目标。没有基类,没有额外的装饰器或类似的东西。此外,出于性能原因,最好在产品环境中完全禁用此功能(假设)
我走了好几条死胡同:
如果您使用浏览器来探索代码库,那么 DevTools 插件可能就是您所需要的。它允许选择页面上的元素并查看其所属的 Angular 组件及其内部状态的相关信息。
如果您不想使用该插件并且只关心开发人员环境,那么这样的事情可能比尝试挂钩更简单
Renderer2
:
function labelNgComponents() {
// Template the label we'll be using so we can
// efficiently clone it for each component.
const labelTemplate = document.createElement('div');
labelTemplate.style.position = 'absolute';
labelTemplate.style.top = 0;
labelTemplate.style.left = 0;
labelTemplate.style.border = '1px solid red';
labelTemplate.style.backgroundColor = 'white';
labelTemplate.style.zIndex = 100;
// Remove labels inserted into the DOM by previous
// runs of this function.
Array.from(document.getElementsByClassName('debug-label'))
.forEach(node => node.remove());
// Find all element nodes in the DOM. These are the
// candidates for Angular component hosts.
const walker = document.createTreeWalker(document.getRootNode(), NodeFilter.SHOW_ELEMENT);
while(walker.nextNode()) {
// We'll use the node itself for DOM manipulation.
const node = walker.currentNode;
// Check if the node is an Angular component host.
// This would also allow us to access state information.
const component = ng.getComponent(node);
if (component != null)
{
// Label the node using its selector (the case
// will vary because `Node.nodeName` is stored
// in all caps).
const label = labelTemplate.cloneNode();
label.textContent = node.nodeName.toLowerCase();
label.classList.add('debug-label');
node.appendChild(label);
}
}
}
当您在调试模式下运行应用程序时,只需将其复制/粘贴到终端中,然后在您想要更新标签时随时执行该函数。