【发布时间】:2019-12-30 00:56:37
【问题描述】:
组件视图中有两个 html 元素。第一个是在组件初始化时创建的。第二个是在 isDivShown == true 时创建的。
let { Component, NgModule, Input, ViewChild } = ng.core;
@Component({
selector: 'my-app',
template: `
<div #myelement1>Element_1</div>
<div #myelement2 *ngIf="isDivShown">Element_2</div>
<button (click)="changeObject()">Change the objects</button>
`,
})
class HomeComponent {
@ViewChild('myelement1') private el1: ElementRef;
@ViewChild('myelement2') private el2: ElementRef;
isDivShown = false;
changeObject() {
this.isDivShown = true;
this.el1.nativeElement.className = 'myCSSclass_1';
this.el2.nativeElement.className = 'myCSSclass_2';
}
}
const { BrowserModule } = ng.platformBrowser;
@NgModule({
imports: [ BrowserModule ],
declarations: [ HomeComponent ],
bootstrap: [ HomeComponent ]
})
class AppModule { }
const { platformBrowserDynamic } = ng.platformBrowserDynamic;
platformBrowserDynamic().bootstrapModule(AppModule);
当我单击按钮并调用 changeObject() 方法时,el1 元素会更改它的类,但 el2 元素会引发错误:
Cannot read property 'nativeElement' of undefined
如何将 ViewChild 用于动态创建的 html 元素?
【问题讨论】:
-
你可以使用新的 ViewChild static true from angular 8 stackoverflow.com/questions/56359504/…
-
所以我想知道,难道 Angular 7 和情人没有这种能力来操纵动态创建的对象吗?给个答案,如果我没有找到更好的解决方案,我会检查它。
-
上面代码中的问题是没有完成你试图访问元素的角度变化检测。为了快速检查,请尝试将 el2.nativeelemet.class 名称包含在 setTimout 中
-
@SuryaPrakashTumma changeObject() 有一些 ajax 请求。在我得到这个 ajax 答案后,我执行 this.isDivShown = true 和 this.el2.nativeElement.className = 'myCSSclass_2'。 (在我目前的情况下,ajax 答案包含我显示为 *ngFor... 的元素数组,但我为这个问题简化了它)。
-
我认为在您的情况下(Ajax)仍未完成更改检测..尝试设置 settimeout 并检查您是否可以访问元素..我的解决方案不是标准方式但我们仍然可以确定问题。
标签: javascript html angular dynamic viewchild