【问题标题】:`querySelectorAll` - returns null value on query with data selector`querySelectorAll` - 使用数据选择器查询时返回空值
【发布时间】:2021-11-30 17:32:00
【问题描述】:

在我的角度指令中,我试图通过data-xxx 值选择元素。但将0 作为长度。

有人帮我理解这个问题吗?

directive.ts:

import {
  Directive,
  OnInit,
  HostListener,
  ElementRef,
  AfterContentChecked,
} from '@angular/core';

@Directive({
  selector: '[autoFocus]',
})
export class AutoFocusDirective implements AfterContentChecked {
  @HostListener('document:keydown', ['$event']) public onKeyUp = ($event) => {
    console.log($event.target);
  };

  constructor(private el: ElementRef<HTMLElement>) {}

  ngAfterContentChecked() {
    this.onFindingTree(this.el.nativeElement);
  }

  onFindingTree(parent) {
    const focusable = parent.querySelectorAll(`[focus=true]`);
    console.log(focusable.length);
  }
}

html:

<div autoFocus>
  <ul>
    <li [attr.data-focus]="true" tabindex="0">1</li>
    <li [attr.data-focus]="true" tabindex="0">
      2
      <ul>
        <li tabindex="0">001</li>
        <li tabindex="0">002</li>
      </ul>
    </li>
    <li tabindex="0">3</li>
  </ul>
</div>

Live Demo

【问题讨论】:

    标签: angular angular-directive


    【解决方案1】:

    像这样更新你的选择器:

    onFindingTree(parent) {
        const focusable = parent.querySelectorAll('[data-focus=true]');
        console.log(focusable.length);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-03
      • 1970-01-01
      • 2020-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多