4

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?

4

1 回答 1

5

您不能ViewChild与动态添加的 HTML 一起使用。

ViewChild仅适用于静态添加到组件模板的组件或指令类型或模板变量。

您也不能@ViewChild()在方法内添加。它仅适用于类级别的属性,并且也必须静态添加。

还为静态添加到组件模板的 HTML 实例化组件和指令。

您可以使用ViewContainerRef.createComponent()动态添加组件。有关示例,请参阅Angular 2 动态选项卡,其中包含用户单击选择的组件

于 2016-10-17T12:10:32.367 回答