5

I', trying to add a html control dynamically to div and after creating the control I would like to perform operations on it by creating viewchild

 @ViewChild('dropDownListReference') myDropDownList: typeOfComponent

able to create in class but in a method after generating the control cannot initialize this

AddLevelClick() {
var el: HTMLElement = document.getElementById('multi-sort-body');
el.innerHTML = "<div #test1></div>";
 @ViewChild('test1') myDropDownList: typeOfComponent    // Unable to create here
}

Any clue on creating ViewChild element locally?

sudhir
  • 1,387
  • 3
  • 25
  • 43
  • Have you found a solution to this? I am having the exact same issue and I'm nowhere near a solution – MrfksIV Aug 24 '17 at 07:44

1 Answers1

6

You can't use ViewChild with HTML added dynamically.

ViewChild only works with component or directive types or template variables added statically to a components template.

You also can't add @ViewChild() inside a method. It works only on class-level properties and has to be added statically as well.

Components and directives are also instantiated for HTML statically added to a components template.

You can use ViewContainerRef.createComponent() to add components dynamically though. For an example see Angular 2 dynamic tabs with user-click chosen components

Mr_Green
  • 40,727
  • 45
  • 159
  • 271
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567