我需要将 html 标签传递给变量,它应该显示 html 元素

I need to pass the html tag in to the variable, and it should display html element

我需要在tableheader中输入元素,headers是从ts文件传来的。我存储了字符串中的标签并存储在变量中并填充到 header 并在 header.

中显示 [HTMLInputElemnt]

那个地方需要输入,怎么实现?? 提前致谢。

声明:

export interface Custom {
  title?: string;
  field?: string;
  default?: 0;
  type?: string;
}

TypeScript 函数

     ngOnInit() {
    this.inputHead = this.htmlToElement('<input value="3">');
    console.log(this.inputHead,"op")

    this._config = {
      name: "Custom",
      properties: this._tableHeader
    };


    this._tableHeader = [
      { title: 'Test Name', field: 'testname', type: 'text', default: 0 },
      { title: 'Initial', field: 'initial', type: 'any', default: 0 },
      { title: this.inputHead, field: 'check', type: 'any', default: 0 },
      { title: this.inputHead, field: 'check', type: 'any', default: 0 }
    ];


    this.testData = [
      { testname: 'Color Test' },
      { testname: 'Humidity Test' },
      { testname: 'Weight Test' },
      { testname: 'Composition Test' },
    ]
    this.cdRef.markForCheck();
  }
   htmlToElement(html:any) {
    var template = document.createElement('template');
    html = html.trim(); // Never return a text node of whitespace as the result
    template.innerHTML = html;
    console.log(template.content.firstChild ,);
    return template.content.firstChild;   
}
}

输出

不确定您要实现的目标,但您可以 return template 而不是 template.content.firstChild 然后使用 属性 绑定而不是字符串插值,如下所示:

<div [innerHTML]="inputHead.innerHTML | sanitizeHtml"></div>

方法 htmlToElement return 是一个 HTMLTemplateElement 类型的对象,您需要绑定到它的 innerHTML 属性。此外,清理该值,因为 Angular 将其识别为不安全值。 这是更新后的 Stackblitz: https://stackblitz.com/edit/angular-n2v9ro