querySelector似乎找不到ng-container内部的元素

时间:2019-04-20 13:28:05

标签: html web dart angular-dart

我正在使用Angle 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。

3 个答案:

答案 0 :(得分:0)

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

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

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

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

有关说明,请参见https://itnext.io/working-with-angular-5-template-reference-variable-e5aa59fb9af

答案 1 :(得分:0)

您可以将其设为独立的组件,我们将其称为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元素的方式。

答案 2 :(得分:0)

它不起作用,因为在您使用“ 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';
相关问题