M
M
mr_blond972019-08-25 17:44:32
JavaScript
mr_blond97, 2019-08-25 17:44:32

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);


isDivShown on initialization == false. When the changeObject() method is called, isDivShown is set to true and then this.el2.nativeElement.className is accessed. An error occurs at this step:

Cannot read property 'nativeElement' of undefined


Example on jsfiddle.

How to use ViewChild for dynamically created elements in Angular2+?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2019-08-25
@Xuxicheta

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';
  }

and of course, it’s not right to do it at all, but
<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>

without calls to html-elements in the
ps methods in your Angular4 example, it’s no longer relevant, the same ViewChild now works a little differently.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question