【问题标题】:querySelectorAll dosen't work with Angular but works in consolequerySelectorAll 不能与 Angular 一起使用,但可以在控制台中使用
【发布时间】:2020-04-01 12:49:10
【问题描述】:

我有一个包含一些复选框的 div,我想使用 querySelectorAll 访问这些复选框,但它似乎在 Angular 中不起作用,尽管它在控制台中有效。

@Component({
  selector: "formly-field-categories-helper",
  template: `
    <div [innerHTML]="categories"></div>
  `
})



ngOnInit() { 
 let inputs = '<input type="checkboxes" name="group" /> test`
 this.categories = this.sanitizer.bypassSecurityTrustHtml(inputs); 
}

ngAfterViewInit() {
  //alerts 0 
  alert(document.querySelectorAll('[name="groups"]').length);
}

但是当我打开 cosole 并运行 document.querySelectorAll('[name="groups"]').length 时,它给了我 192(不是 0)

您可以从这里查看完整代码 https://github.com/goblins-tech/almogtama3/blob/master/src/app/content/editor.ts#L248

注意 使用setTimeout 将解决问题,但我不使用它。我只想在 DOM 完全创建后运行代码。

setTimeout(() => {
      alert(document.querySelectorAll('[name="groups"]').length);
    }, 5000);

注意 ngAfterViewChecked 运行多次,所以我避免使用它。

在下一步中,我会将document.querySelectorAll 替换为nativeElement.querySelectorAll

【问题讨论】:

    标签: angular document selectors-api queryselector


    【解决方案1】:

    美好的一天!

    你试过这样的吗?

    ngAfterViewInit() {
      setTimeout(() => {
        alert(document.querySelectorAll('[name="groups"]').length);
      });
    }
    

    【讨论】:

    • 工作,但我想要另一个没有 setTimeout 的解决方案,我只想在 DOM 完成时运行代码
    猜你喜欢
    • 1970-01-01
    • 2015-11-12
    • 2014-03-20
    • 1970-01-01
    • 2012-11-20
    • 2017-11-07
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多