【问题标题】:querySelector does not seem to find elements inside ng-containerquerySelector 似乎没有在 ng-container 中找到元素
【发布时间】:2019-04-20 13:28:04
【问题描述】:

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

【问题讨论】:

  • 在模板中这样做可能会更好。你到底想对那个 div 做什么?
  • @mbojko 我正在尝试在容器内绘制饼图:`` final DivElement _container = document.querySelector('#' + item.elementID); PieChart(_container).draw(result.chartData, chartDrawingOptions); ```

标签: html web dart angular-dart


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    你可以把它做成一个单独的组件,我们称之为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 元素的方式。

    【讨论】:

    • 但是有没有办法只使用一个组件来实现这一点?
    【解决方案3】:

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

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

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

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

    请参阅https://itnext.io/working-with-angular-5-template-reference-variable-e5aa59fb9af 了解说明。

    【讨论】:

    • 重要的是要注意我正在迭代一个列表(请参阅顶部的“ngFor”)。因此,每个 div 元素引用名称在列表中必须是唯一的。这个怎么办?
    • 但是如果我们要查询的元素在组件内部呢?
    【解决方案4】:

    AfterViewChecked 无效。使用 AfterViewInit

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    • 2011-12-26
    • 1970-01-01
    相关资源
    最近更新 更多