How to create @ViewChild temporary variable in a method in Angular 2?

sudhir picture sudhir · Oct 17, 2016 · Viewed 10.4k times · Source

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?

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Oct 17, 2016

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