There are two html elements in components view. The first one is being created on component initialization. The second one is being created when 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);
When I click the button and the method changeObject() is being called the el1 element changes it's class but the el2 element thwrows an error:
Cannot read property 'nativeElement' of undefined
How do I use ViewChild for dynamic created html elements?