htmlwebdartangular-dart

querySelector does not seem to find elements inside ng-container


I am developing a web application using angular dart.

I am trying to find a 'div' element inside the component using document.querySelector() and I am trying to modify(add some content to) its body.

But it doesn't seem to find the 'div' element.

Here is my html:

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

Here is my component method which tries to modify the 'div':

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

It always prints the '_container' as 'null'

I tried removing the ng-container and having only the 'div' in the page like below and it seems to work!.

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

What is the problem?

TIA.


Solution

  • You can make it a separate component, let's call it app-chart:

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

    In the AppChartComponent declare necessary input(s), and inject ElementRef in the constructor:

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

    this.ref.nativeElement is how you can access the DOM element from inside.