了解从

时间:2019-01-10 15:00:16

标签: angular typescript

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

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

然后我在.ts一侧使用@Input来获取该值

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

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

1 个答案:

答案 0 :(得分: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元素以及一些可以添加到指令的自定义后缀来创建自定义名称。