如何在Angular 2+中将ViewChild用于动态创建的html元素?

时间:2019-08-25 16:09:30

标签: javascript html angular dynamic viewchild

组件视图中有两个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元素?

2 个答案:

答案 0 :(得分:0)

您可以改用.populate()来创建与[hidden]相反的onInit上的dom节点。

*ngIf

答案 1 :(得分:0)

Qucik解决

setTimeout(() => {
      this.el2.nativeElement.className = 'myCSSclass_2';
 },10);