Answer the question
In order to leave comments, you need to log in
How to use ViewChild for dynamically created elements in Angular2+?
There are two html elements in the component template, the first one is displayed when the component is initialized, the other one is displayed by the *ngIf="isDivShown" condition.
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);
Cannot read property 'nativeElement' of undefined
Answer the question
In order to leave comments, you need to log in
So you change the variable, and then immediately expect el2 to appear, of course it's not there, give Angular time to do its job.
public changeObject() {
this.isDivShown = true;
setTimeout(() => this.changeClasses());
}
private changeClasses() {
this.el1.nativeElement.className = 'myCSSclass_1';
this.el2.nativeElement.className = 'myCSSclass_2';
}
<div [class.myCSSclass_1]="isDivShown">Element_1</div>
<div *ngIf="isDivShown" [class.myCSSclass_2]="isDivShown">Element_2</div>
<button (click)="isDivShown = true">Change the objects</button>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question