使用 Angular 代码动态地将 HTML 注入到现有 DOM 中

问题描述 投票:0回答:1

我在 Angular 应用程序中使用 Bootstrap Tables。要在单元格中呈现自定义按钮,我必须从 Angular 组件编写 HTML 代码,将 HTML 定义为字符串。但是这样我就无法绑定组件功能了。

例如,我想通过组件代码以编程方式添加此 HTML

elem.innerHTML = "<button (click)='myFunction(index)'>
                     Alert {{index}} 
                 </button>";

其中

myFunction
是分量函数。此代码将不起作用,因为它将被作为静态 HTML 处理。

当我使用旧的 AngularJS 时,我设法解决了这个问题。这是我采用 AngularJS 和 Bootstrap Table 的工作解决方案。

/** function that renders the button */
const formatButton = function(row_element, index)
{
 var html = `<button onClick="angular.element(this).scope().myFunction(${index})">
                Alert ${index} 
            </button>`;
}

/** init, create the table */
function init(){
var table_columns:[
   {
    title:"Column 1",       // th name
    formatter: formatButton // render cells
   }];

jQuery("#table-id").bootstrapTable(
  {
   columns: table_columns,
   data:data
  });

}

/** function called by the button */
$scope.myFunction(index)
 { alert(index); }

这会呈现这样的表格。单击按钮,将调用

$scope.myFunction()
,显示带有行索引的警报

==============
|             |
|  Column 1   |
|             |
=============
|  Alert 0   |
--------------
|   Alert 1  |
_____________

在现代Angular中,我没有$scope,所以我真的不知道如何从注入的html访问组件函数

myFunction()
,可以通过简单的
onClick
调用,而不是通过
(click)

调用
angular angular-components bootstrap-table
1个回答
0
投票

我就是这样解决的。请评论我的解决方案,说明它是否合适或有任何缺点。

这些步骤:

  1. 将我想要注入的 HTML 作为单独的组件
    @Component({
      selector: 'alert-button',
      template: ` <button (click)="myFunction(index)">
                            Alert {{index}}
                    </button>   
                `,
    
    })
    export class AlertButton{
      @Input() index: string = '';
    
      constructor() 
      {}
    
      public myFunction(text:string)
       { alert(text); }  
    }
  1. 在容器组件上,导入一些Refs。
import { ElementRef, ViewContainerRef, ComponentRef } from '@angular/core';
import {AlertButton} from ...

  constructor(private el: ElementRef,
              private _ViewContainerRef: ViewContainerRef
             ) 
  {}
  1. 将 HTML 作为字符串注入。您可以注入任何您喜欢的 HTML,稍后您将引用它,并替换为组件。还写下组件所需的参数。
function injectHtml(value)
{
  var html = ` <alert-button index="${value}"></alert-button>`;
  return html;
}
  1. 注入所有 HTML 后,将其替换为真正的 Angular 组件。
// render Angular components

// retrieve placeholders elements
var elements = (<HTMLElement>self.el.nativeElement).querySelectorAll('alert-button');
for (let c in elements)
 {
  var element = elements[c]; 

  // create the angular component
  const component: ComponentRef <any> = self._ViewContainerRef.createComponent(CheckoutIdButton);

  // get attributes from the placeholder, and pass them to the component  
  var attrs = element.getAttributeNames();
  for(let a in attrs)
    {
     var attr_name = attrs[a]; // should be "index"
     component.instance[attr_name] = element.getAttribute(attr_name);
    }
  // get the HTML element from the component
  const new_element: HTMLElement = component.location.nativeElement;
  new_element.contentEditable = 'false';  
  // append the new element to the placeholder
  element.appendChild(new_element);
               }

© www.soinside.com 2019 - 2024. All rights reserved.