Angular 7, как получить все дочерние элементы с помощью пользовательских атрибутов директив - PullRequest
0 голосов
/ 11 октября 2019

Может кто-нибудь помочь мне, как получить все элементы с пользовательским атрибутом в угловом компоненте?

Я знаю, как получить список угловых компонентов, т. Е.

@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>

Здесь мне нужен компонент, чтобы получить все элементы, которые имеют атрибут [tooltip]?

Спасибо

1 Ответ

0 голосов
/ 11 октября 2019

Я почти уверен, что вы можете добиться этого, выполнив следующие действия:

@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)
    })
  }

tooltip.directive.ts

constructor (public hostElem: ElementRef<HTMLInputElement>) { }
...