Angular 2 innerHTML(单击)绑定 [英] Angular 2 innerHTML (click) binding
问题描述
我有一个很大的html菜单,因此我决定绑定以便能够进行多个子菜单下拉菜单并避免html代码重复.父>子(也是父)>子...
I had such a large html menu that I decided to binding to be able to make several submenu dropdown and avoid html code duplication. Parent > child (which is parent too) > child...
对于上下文:在ng2_msList/msList.components.ts中,将ColumnsManagements.ts作为this.ColumnsManagementInstance导入. innerHTML菜单正确显示在ng2_msList/pages/list.html中:
For the context : In ng2_msList/msList.components.ts, ColumnsManagements.ts is imported as this.ColumnsManagementInstance. The innerHTML menu is displayed properly, in ng2_msList/pages/list.html :
<!-- COLUMNS DROPDOWN BUTTON -->
<ul [innerHTML]="msList.ColumnsManagementInstance.columnMenu" class="dropdown-menu" role="menu"> </ul>
使用(在我的代码的非常简化的版本中):(感谢此 Stack 问)
With (in a very simplified version of my code) : (Thanks to this Stack Q)
setHtmlColumnsMenu() {
var self = this;
var htmlcolumnsmenu = '';
[...]
htmlcolumnsmenu += this.createColumnsList(this.getNoneRelationalColumns(true));
// which return something like a lot of html content and sometime in it :
// <a href="javascript:;" (click)="msList.ColumnsManagementInstance.toogleColumn(column)">
[...]
return htmlcolumnsmenu;
}
BUT(click)="msList.ColumnsManagementInstance.toogleColumn(column)"(以前在html内容中)不再起作用.它在视图中作为标记中的简单文本编写(在innerHtml之前,它没有显示).
BUT (click)="msList.ColumnsManagementInstance.toogleColumn(column)" (previously in the html content) is not working anymore. It's writing in the view as simple text in tag (before the innerHtml it was not displayed).
我无法找到使它再次运行的方法.我测试了多种调用函数的方法,或者在 Ang文档部分,例如此处. 这些示例调用一个很容易在同一文件/上下文中设置的函数(click)="MyAction()",但是根据我的上下文,我无法找到一种正确调用它的方法.
I can't reach a way to make it works again. I test multiple ways to call the function or as I found in web links as on the Ang Doc Section, here for example. These examples call a function which is set in the same file/context very easily (click)="MyAction()" but with my context I can't get a way to call it properly.
应用程序架构可能不像Angular2点击通话所期望的那样.
The app architecture is maybe be not as Angular2 click call would expect.
推荐答案
这是设计使然. Angular不会以任何方式处理由[innerHTML]="..."
添加的HTML(清理除外).它只是将其传递给浏览器而已.
That's by design. Angular doesn't process HTML added by [innerHTML]="..."
(except sanitization) in any way. It just passes it to the browser and that's it.
如果要动态添加包含绑定的HTML,则需要将其包装在Angular2组件中,则可以使用例如ViewContainerRef.createComponent()
If you want to add HTML dynamically that contains bindings you need to wrap it in a Angular2 component, then you can add it using for example ViewContainerRef.createComponent()
有关完整示例,请参见 Angular 2带有用户单击所选组件的动态选项卡
For a full example see Angular 2 dynamic tabs with user-click chosen components
较少的Angulary方法是注入ElementRef
,使用
A less Angulary way would be to inject ElementRef
, accessing the added HTML using
elementRef.nativeElement.querySelector('a').addEventListener(...)
这篇关于Angular 2 innerHTML(单击)绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!