简体   繁体   English

角度打字稿如何将字符串转换为html对象并将其传递给变量

[英]Angular typescript how to convert string to html object and pass it to variable

I have a function witch gets html content from file as a string. 我有一个功能女巫从文件中获取html内容作为字符串。 After that I made it as a html object. 之后,我将其作为html对象。 I can clearly see it in my console that it works. 我可以在控制台中清楚地看到它的工作原理。 How to pass it from a service to a div element ? 如何将其从服务传递到div元素?

nav.service.ts : 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
        });
      }
    }

What I get now by adding {{navSrv.html}} in my component : 我现在通过在组件中添加{{navSrv.html}}得到的结果:

在此处输入图片说明

What I want to get : 我想要得到的是:

Hello 你好

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

在此处输入图片说明

How to get htmlObject and use it as a variable ? 如何获取htmlObject并将其用作变量?

you can do it like follow if you want it in div only then 如果您只想在div中使用,则可以按照以下步骤进行操作

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

Apart from this you can also do it like below : 除此之外,您还可以像下面这样:

<div #divID ></div>

And then bind it like this way 然后像这样绑定它

@ViewChild('divID') divID: ElementRef;

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

The second part is useful when the html string is very much large. 当html字符串很大时,第二部分很有用。

EDIT 编辑

As your requirement if you have <script> tag then you can do if as follows 如果您具有<script>标记,则可以按照以下要求进行操作

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM