知道正在调用组件的html

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

在Angular5项目的.ts文件中,我需要知道添加组件的html的名称(为了为这些组件中的某些按钮创建唯一的名称)所以我的html结束了以下内容:

<my-component data-myattribute="thishtmlfile"  ></my-component>

然后我在.ts方面使用了@Input来获取这个值

但我想知道是否有一种方法可以在组件本身的代码中自动知道我的组件的名称。

Reflect对象对我来说效果不佳,但我愿意再试一次;)

angular typescript
1个回答
1
投票

我做了类似的事情,为我的HTML元素提供了唯一的ID。在这里,如果它可以有任何帮助:

import { AfterViewInit, Directive, ElementRef, Input, Renderer2 } from '@angular/core';

@Directive({
  // tslint:disable-next-line:directive-selector
  selector: '[app-path]'
})
export class AppPathDirective implements AfterViewInit {

  @Input('app-path') path: string & string[];

  @Input('app-path.ignoreWarning') private _ignoreWarning = false;

  get shouldWarn() {
    return this._ignoreWarning === false;
  }

  element: HTMLElement;

  constructor(
    private renderer: Renderer2,
    el: ElementRef<HTMLElement>,
  ) {
    this.element = el.nativeElement;

    if (this.element.id) {
      if (this.shouldWarn) {
        console.warn(`Custom business error`);
      }
    }
  }

  ngAfterViewInit() {
    this.setElementCustomId();
  }

  setElementCustomId() {
    let name = '';

    // Crawl up to the parent feature with the renderer
    let currentElement: HTMLElement = this.element;
    while (currentElement && currentElement.tagName && !currentElement.tagName.toLowerCase().startsWith('app-')) {
      currentElement = this.renderer.parentNode(currentElement);
    }

    if (currentElement && currentElement.tagName) {
      name += currentElement.tagName.toLowerCase()
      // remove 'app-'
        .replace('app-', '') + '-';
    } else {
      if (this.shouldWarn) {
        console.warn(`Custom error : No parent feature tag has been found : the name of the feature won't appear in the ID`);
      }
    }

    // Append the HTML component type to the name
    const htmlElementName: string = this.element.constructor.name.toLowerCase();
    if (!htmlElementName.includes('html') || !htmlElementName.includes('element')) {
      // If it is not an HTML element, do nothing and throw an error
      if (this.shouldWarn) {
        console.warn(`Custom error : No HTML Element was found for the app-path : the element type won't appear in the ID`);
      }
    } else if (htmlElementName === 'htmlelement') {
      // Custom Angular / Material element : ignore.
    } else {
      // Else, append the element type
      name += htmlElementName.replace(/(html|element)/g, '');
    }

    // Append the custom suffix to the name
    let customSuffixe = '';
    if (typeof this.path === 'string' && this.path) {
      customSuffixe += '-' + this.path;
    } else if (this.path && this.path.length) {
      this.path.forEach(item => customSuffixe += '-' + item);
    }
    name += customSuffixe;

    this.renderer.setAttribute(this.element, 'id', name);
  }
}

这将根据您所在的当前组件,指令所针对的HTML元素以及可以附加到指令的某些自定义后缀创建自定义名称。

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