繁体   English   中英

querySelector 似乎没有在 ng-container 中找到元素

[英]querySelector does not seem to find elements inside ng-container

我正在使用 Angular Dart 开发 Web 应用程序。

我正在尝试使用 document.querySelector() 在组件内找到一个“div”元素,并且我正在尝试修改(添加一些内容)它的主体。

但它似乎没有找到“div”元素。

这是我的 html:

<ng-container *ngFor="let item of list">
  <ng-container *ngIf="item.canShowChart">
    <div [id]="item.elementID" class="chart"></div>
  </ng-container>
</ng-container>

这是我尝试修改“div”的组件方法:

  void drawChart() {
    for (final item in list) {
      if (!item.canShowChart) {
        continue;
      }
      final DivElement _container = document.querySelector('#' + item.elementID);
      print(_container);
    }
  }

它总是将 '_container' 打印为 'null'

我尝试删除 ng-container 并在页面中只有“div”,如下所示,它似乎有效。

<div [id]="item.elementID" class="chart"></div>

问题是什么?

TIA。

它不起作用,因为在您使用“querySelectorAll”时,angular 尚未将 ng-container 加载到 DOM。 您应该将代码放在“AfterViewChecked”生命周期挂钩中。

export class ImageModalComponent implements OnInit, AfterViewChecked{
  //AfterViewChecked
  ngAfterViewChecked {
    void drawChart() {
    for (final item in list) {
      if (!item.canShowChart) {
        continue;
      }
      final DivElement _container = document.querySelector('#' + item.elementID);
      print(_container);
    }
  }
 }
}

确保像这样导入“AfterViewChecked”;

import { Component, OnInit, AfterViewChecked } from '@angular/core';

您可以将其作为一个单独的组件,我们称它为app-chart

<ng-container *ngFor="let item of list">
  <app-chart *ngIf="item.canShowChart" [item]="item">
  </app-chart>
</ng-container>

在 AppChartComponent 中声明必要的输入,并在构造函数中注入 ElementRef:

@Input() item: any;
constructor(private ref: ElementRef) {}

this.ref.nativeElement是您从内部访问 DOM 元素的方式。

切勿使用querySelector在模板中查找元素。 Angular 和 DOM 是两个独立的范例,您不应该混合使用它们。

要在模板中查找元素,请使用对元素的引用。

<div #chartContainer class="chart"></div>

然后您可以从您的代码中引用div

有关解释,请参阅https://itnext.io/working-with-angular-5-template-reference-variable-e5aa59fb9af

AfterViewChecked 无效。 使用 AfterViewInit

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM