Sab*_*esh 7 html web dart angular-dart
我正在使用 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>
Run Code Online (Sandbox Code Playgroud)
这是我的组件方法,它尝试修改“div”:
void drawChart() {
for (final item in list) {
if (!item.canShowChart) {
continue;
}
final DivElement _container = document.querySelector('#' + item.elementID);
print(_container);
}
}
Run Code Online (Sandbox Code Playgroud)
它总是将“_container”打印为“null”
我尝试删除 ng-container 并在页面中仅包含“div”,如下所示,它似乎有效!
<div [id]="item.elementID" class="chart"></div>
Run Code Online (Sandbox Code Playgroud)
问题是什么?
TIA。
小智 5
它不起作用,因为在您使用“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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
确保像这样导入“AfterViewChecked”;
import { Component, OnInit, AfterViewChecked } from '@angular/core';
Run Code Online (Sandbox Code Playgroud)
您可以将其作为一个单独的组件,我们称之为app-chart
:
<ng-container *ngFor="let item of list">
<app-chart *ngIf="item.canShowChart" [item]="item">
</app-chart>
</ng-container>
Run Code Online (Sandbox Code Playgroud)
在 AppChartComponent 中声明必要的输入,并在构造函数中注入 ElementRef:
@Input() item: any;
constructor(private ref: ElementRef) {}
Run Code Online (Sandbox Code Playgroud)
this.ref.nativeElement
这就是从内部访问 DOM 元素的方式。