代码之家  ›  专栏  ›  技术社区  ›  Mukil Deepthi

Angular 7如何使用自定义指令属性获取所有子元素

  •  0
  • Mukil Deepthi  · 技术社区  · 6 年前

    有人能帮我如何在角度分量中获得所有具有自定义属性的元素吗?

    我知道如何获得角度组件列表,即。

    @ViewChildren(CdkDropList) dropLists: QueryList<CdkDropList[]>;
    

    但不确定如何获取具有自定义指令的元素列表。比如在我的例子中:

      <div>
        <input type="text"/>&nbsp;<i class="fa fa-info" [tooltip]="one"></i>
      </div>
      <div>
        <input type="text"/>&nbsp;<i class="fa fa-info" [tooltip]="two"></i>
      </div>
      <div>
        <input type="text"/>&nbsp;<i class="fa fa-info" [tooltip]="three"></i>
      </div>
      <div>
        <input type="text"/>&nbsp;<i class="fa fa-info" [tooltip]="four"></i>
      </div>
      <div>
        <input type="text"/>&nbsp;<i class="fa fa-info" [tooltip]="five"></i>
      </div>
    

    在这里,我需要组件来获取所有具有[工具提示]属性的元素?

    谢谢

    0 回复  |  直到 6 年前
        1
  •  1
  •   Andrei Gătej    6 年前

    我很确定你可以通过这样做来实现它:

    @Component({ /* ... */ })
    export class FooComponent {
     @ViewChildren(TooltipDirective, { read: ElementRef }) inputs: QueryList<ElementRef<HTMLInputElement>>;
    
      ngAfterViewInit () {
        this.inputs.forEach(input => {
          console.log(input.nativeElement)
        })
      }
    }
    

    编辑:获取属性值

    @ViewChildren(TooltipDirective) inputsDirs: QueryList<TooltipDirective>;
    
      ngAfterViewInit () {
        this.inputsDirs.forEach(inputDir => {
          // The value of the attribute
          console.log(inputDir.tooltip)
          // The host element
          console.log(inputDir.hostElem.nativeElement)
        })
      }
    

    工具提示。指令。输电系统

    constructor (public hostElem: ElementRef<HTMLInputElement>) { }
    
    推荐文章