[英]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.