【问题标题】:Angular typescript how to convert string to html object and pass it to variableAngular typescript如何将字符串转换为html对象并将其传递给变量
【发布时间】:2018-09-29 16:02:01
【问题描述】:

我有一个函数可以从文件中获取 html 内容作为字符串。之后我把它做成了一个 html 对象。我可以在控制台中清楚地看到它有效。如何将它从服务传递到 div 元素?

nav.service.ts

html: string;
      public  getZipFileContent(urlPath:string, pathInZip:string, ) {
        getFileContentFromRemoteZip(urlPath, pathInZip, (content) => {
          console.log(content);
          let html = content; 
          let htmlObject = document.createElement('div');
          htmlObject.innerHTML = html;
          console.log(htmlObject);
          this.html = html; // it's a string
          this.html = htmlObject // error : can't asign string as HTMLdivElement
        });
      }
    }

我现在通过在我的组件中添加 {{navSrv.html}} 得到什么:

我想得到什么:

你好

Console.log 来自:console.log(htmlObject);

如何获取htmlObject并将其用作变量?

【问题讨论】:

标签: javascript angular typescript javascript-objects


【解决方案1】:

为此,您可以使用 innerHTML 它将确保您的 html 正确显示:

<div [innerHTML]="navSrv.html"></div>

【讨论】:

  • 天啊.. 2 小时这个??讨厌这种情况。谢谢
  • 如果在那个 html 中是写 js 的
【解决方案2】:

如果你想要它在 div 中,你可以像follow一样这样做

<div [innerHtml]="navSrv.html"></div>

除此之外,您还可以像下面这样:

<div #divID ></div>

然后这样绑定

@ViewChild('divID') divID: ElementRef;

loadHtml(){
    this.divID.nativeElement.innerHTML = this.html;
}

当 html 字符串非常大时,第二部分很有用。

编辑

如果您有&lt;script&gt;标签,则可以按照您的要求进行操作,如下所示

const element = document.createRange().createContextualFragment(this.html);
this.divID.appendChild(fragment);

【讨论】:

  • 如果 HTML 字符串中有
  • 你现在得到了什么?我认为它会起作用,但我怀疑标签下的代码不起作用
  • 现在我正在使用
    。我的 navSrv.html 是带有大量 javascript 代码的 .html 文档。我得到 javascript 作为字符串。
  • 检查我更新的答案。也许你会得到答案。
  • 我收到错误 "Cannot read property 'nativeElement' of undefined" 。我在课堂上写道:@ViewChild('html') html: ElementRef; loadHtml(){ this.html.nativeElement.innerHTML = this.navSrv.html; }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-02
  • 2021-08-13
  • 1970-01-01
  • 2016-05-23
  • 2010-09-15
  • 1970-01-01
相关资源
最近更新 更多