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?
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