将组件选择器添加为 Angular 中每个自定义组件上方的文本

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

在开发 Angular 应用程序时,我反复使用检查器寻找组件选择器(示例:

app-custom-component
)。这让我思考。我可以简单地在
top:0, left:0
上的 Angular 中的每个组件上方显示选择器的值吗?我想在不修改组件的情况下实现这一目标。没有基类,没有额外的装饰器或类似的东西。此外,出于性能原因,最好在产品环境中完全禁用此功能(假设)

我走了好几条死胡同:

  • PLATFORM_DIRECTIVES 可以说是最合适的,但它已被弃用
  • 提供自定义 Renderer2 - 这感觉是错误的,似乎可能会导致问题(不知道我在做什么)
  • 指令上的选择器“*” - 这是 LLM 建议的,但根本不是一个东西
angular
1个回答
0
投票

如果您使用浏览器来探索代码库,那么 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);
    }
  }
}

当您在调试模式下运行应用程序时,只需将其复制/粘贴到终端中,然后在您想要更新标签时随时执行该函数。

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